Counting digits using while loop

E.O. picture E.O. · Jul 6, 2011 · Viewed 26k times · Source

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)?

Answer

Zan Lynx picture Zan Lynx · Jul 6, 2011

In 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:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double n;
    cout << "Enter a number: ";
    cin >> n;

    cout << "Log 10 is " << log10(n) << endl;
    cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
    return 0;
}