how to get lenght of number

how to get length of a number.

like if i input number 1032 (integer type data) how to know that it's a 4 digit number.
like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <conio.h>
using namespace std; 

int main() {
string number;

cout << "Enter a number: ";
cin >> number;

cout << "The length of the number you just entered is " << number.length() << " lol." << endl;

cout << "press any key to exit..."; 

_getch(); 
return 0; 
Last edited on
thats such a lame way to do it! If you aren't doing this in a hurry i say take the time and think of creating your own function to take length of a number, its really fun
@mussaAli i asked for a int numbers length not for string length.

if someone knows then please tell me.

and i will try it at my own also.
1
2
3
4
int x;
cin >> x;
int lengthCount = 0
for(; x != 0; x /= 10, lengthCount++);


It keeps dividing by 10, and as long as the number is not 0 it will add to the count and then divide by 10 again. If the user enters 0, it reports the length as zero, for all other single digit numbers it would report it as 1.
Last edited on
@time to c: Did you execute the mussaAli's program? You enter a number (an integer) and the program see that number that you entered as a string. The program is doing his job even if he works with strings. I think is more faster to work with numbers as strings.
But if you want to see the length of an integer (of a number) without working with strings, look at the Intrexa's post.

Here is a simple way to do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;
int lengthfunction(int number); //prototype
int main()
{   
       int number;
       cout<<"Enter the number: ";
       cin>>number;
       cout<<"The length of that number is: "<<lengthfunction<<"\n";
       return 0;
}
int lengthfunction(int number)
{    
      int counter=0;
      while(number)
     {        
            number=number/10;
            counter++;
      }
      return (counter);
}


Note: I didn't compiled the program. I don't have an IDE installed on my computer.
Topic archived. No new replies allowed.