468,513 Members | 1,759 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,513 developers. It's quick & easy.

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

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
2 3921
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
9,056 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.

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.

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
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.