counting # of digits

Mar 25, 2010 at 7:55am
Hello,

I have been trying to count the number of digits in an integer. I know I am close, but I am not quite sure what I am doing wrong. Could someone please point me in the right direction?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using namespace std;
int main()
{
  long A;
  long B;
  int n=0;

  cout << "enter value: " ;
  cin >> A;
  cin.ignore();

    if (1000000000 < A >= 0) {
    ++n;    
    (A /= 10);
    cout << A << " is " << n << " digits long" << endl;
    }
}

My output is always 1 for A. I know I am just misunderstanding something simple.

Thank you in advance for any help on this problem.
Mar 25, 2010 at 8:33am
If you use an if loop, it will only execute once if the condition is true. Then it won't execute again.
Mar 25, 2010 at 9:38am
Try the below code snippet

#include <iostream>
using namespace std;
int main()
{
long A;
int n=0;

cout << "enter value: " ;
cin >> A;
cin.ignore();

while(A)
{
++n;
A /= 10;

}
cout << "entered value is " << n << "digit long" << endl;
}
Mar 25, 2010 at 12:35pm
mogha:

so in other words the number zero has zero digits.

(we avoid just giving solutions to people since they don't typically learn anything that way).
Topic archived. No new replies allowed.