I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:
int x;
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
count++;
x = x/10;
}
From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.
Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?
If
x
is an integer, and by "built in function" you aren't excluding logarithms, then you could doIn your particular example you could read the number as a string and count the number of characters.
But for the general case, you can do it your way or you can use a base-10 logarithm.
Here is the logarithm example:
Given a very pipelined cpu with conditional moves, this example may be quicker:
as it is fully unrolled. A good compiler may also unroll the while loop to a maximum of 10 iterations though.
You could read the user input as a string, and then count the characters? (After sanitising and trimming, etc.)
Alternatively, you could get a library to do the hard work for you; convert the value back to a string, and then count the characters: