I'm new to c++ and I've got a question. I want to make a c++ program that displays the number of digits in a number entered by the user and I want to make sure he doesn't enter alphabetical character.(For this I use the isdigit() function).
I know I can use strlen to find out the length of a string. But is something like this for numbers? I mean a function or something that returns the number of digits in a number?
I would appreciate any reply that can help me out.
Thanks in advance!
This is a homework question, so forget the string stuff.
If the user did not enter a number like he should have, then cin will be in a fail state. You need to do something like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
unsignedint n;
while (true)
{
// tell the user what to do
cout << "Please enter a non-negative integer: ";
// get the number
// if everything is ok, then we're done
if (cin >> n) break;
// fix cin to work again
cin.clear();
// get rid of the incorrect input (not a number)
cin.ignore( 1000, '\n' );
// complain about it to the user
cout << "Hey, that was not correct!\n";
}
cout << "Good job! You entered the number " << n << "\n";
To get the number of digits, count how many times you can divide the number by ten before it becomes zero, and add one.
@hamsterman
Your algorithm indicates that my number "0" has zero digits. (Count should always start at one. :-)
Thank you both for your posts!
@Duoas My program works. And why should I forget the string stuff ?Before trying this I made a program that checks whether the user had entered a number or not with isdigit() function and I thought the function would help me with this too.
@hamsterman The first method you used is allright for me but the others...I didn't get it. If you want, will you please explain me so I can understand?
I want to use all the methods well and by the way, this isn't a homework.