By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,720 Members | 2,237 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,720 IT Pros & Developers. It's quick & easy.

Ensuring input is an integer (or converting string to an int)

P: 98
Hi,

I'm trying to write a bit of code to ensure that a user inputs only digits (an int) when promtped.

I have been successful using a char array and tested it using isdigit, but then i need to pass it to a function as only an integer.

I'd appreciate any help with either how to test whether an input is an interger or to change a char array to an int. (Note, I'm not asking for someone to write the program for me, just for suggestions and explanations of how to use them)

Thanks for any help.
Sep 20 '06 #1
Share this Question
Share on Google+
2 Replies


P: 61
Keep on accessing each element of the string and check whether it falls in the range 48 to 57. Because ASCII code of '0' character is 48 and '9' character is 57. If it doesn't fall in the above mentioned range then given input is not a number.

If the given string is a number then use atoi() API to convert it to an integer and atol() to convert it to long integer.
Sep 20 '06 #2

Banfa
Expert Mod 5K+
P: 8,916
use the function strtoul (or strtol for signed values).

This will simultaneously convert the digits to an integer and provide a check that all characters are valid in any base.

Declaration

unsigned long strtoul( const char *nptr, char **endptr, int base );

usage

Expand|Select|Wrap|Line Numbers
  1. char digits[] = "12345";
  2. char *pEnd;
  3. int value;
  4.  
  5. value = (int)strtoul( digits, &pEnd, 10 );
  6.  
The pointer pEnd is set to point at the character on which the conversion terminated, in this case it will point to the string terminator because all digits are valid. I cast the output to the integer type I require.

It the string was "1234Hello" then pEnd will end up pointing to the H of hello so if the user is only supposed to put in valid digits the conversion will always end of the string terminator for a valid string.
Sep 20 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.