Can anyone tell me about how can i check the number of digits which a user has just put in
for example
input: 21212
number of digits = 5
thanks
This is a discussion on count numbers input within the C Programming forums, part of the General Programming Boards category; Can anyone tell me about how can i check the number of digits which a user has just put in ...
Can anyone tell me about how can i check the number of digits which a user has just put in
for example
input: 21212
number of digits = 5
thanks
Depends how there stored.
Assuming they're in a string, you can use strlen(), or if you want to validate that they are actually 5 numbers (as opposed to 4+ 1 letter), you'll have to try something like
- looping through the array, checking each one with isdigit()
- convert to a numeric variable via atoi() or atol() and check the return code to make sure it worked.
I'm sure there's a few other ways too.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
you could also use -->
Code:if(num>=0 && num<=9) digits=1; if(num>=10 && num<=99) digits=2; if(num>=100 && num<=999) digits=3; //so on..
-
Usually it's easiest to place the number in an array and count the valid elements, but if you want to count the digits of a number without converting it to an array you can make a copy and break it down, counting each digit:
-PreludeCode:/* get input and make a copy */ for ( x = 0; copy != 0; x++ ) copy /= 10; printf ( "%d contains %d digits\n", input, x );
My best code is written with the delete key.
If you want to get complicated/fancy and you are only talking about integer input (no floating point stuff), you can use logarithms to do this:
Outputs 5, change iValue to 100000 for example and it outputs 6. Change it to whatever you want and see how it behaves. Like I said, the caveat is that this only works for integers.Code:#include <cmath> #include <iostream> using namespace std; int main() { int iValue = 99999; cout << "Number of digits for " << iValue << " is " << floor(log10( iValue )+1.0) << endl; }
I used to be an adventurer like you... then I took an arrow to the knee.
Crap... sorry about that, I thought I was on the C++ board. Anyway, my response still applies:
Code:#include <math.h> #include <stdio.h> int main() { int iValue = 99999; printf( "Number of digits for %d is %d\n", iValue, (int) floor(log10( iValue )+1.0) ); return 0; }
Last edited by hk_mp5kpdw; 05-10-2002 at 09:51 AM.
I used to be an adventurer like you... then I took an arrow to the knee.