471,084 Members | 828 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,084 software developers and data experts.

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


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
2 3971
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
9,065 Expert Mod 8TB
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.


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


Expand|Select|Wrap|Line Numbers
  1. char digits[] = "12345";
  2. char *pEnd;
  3. int value;
  5. value = (int)strtoul( digits, &pEnd, 10 );
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.

Similar topics

2 posts views Thread by Tomas Deman | last post: by
6 posts views Thread by AC 74 | last post: by
13 posts views Thread by sam | last post: by
11 posts views Thread by Peter Olcott | last post: by
13 posts views Thread by liujiaping | last post: by
4 posts views Thread by mthread | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.