Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to detect if int input is not a digit

Status
Not open for further replies.

darr01

Programmer
Oct 24, 2001
28
0
0
MY
Hi, guys. How do you detect whether an input with 'int' datatype is an integer and not letters or other characters?
Is there a built-in function in C that allows one to do this?

I know that if I use the 'char' datatype, I can check whether the input is a digit or not by using isdigit(int c) but I need to ask the user to input an integer that can be more than 5,000 in value. If I use char as the datatype, I can only check the first digit and not the rest.

Thanks in advance,
Darr

 
You could read the input into a string variable then either use your own code to test for non-digit characters then use atoi() to convert the string to an integer or you could use strtol() to convert the string to a long, which you could cast to an int, and have strtol do the sanity checking (atoi doesn't check for non-numeric input in the string whereas strtol does).

Cheers
 
I think u can add a line to warn user, like this:

printf( "Please input a integer(not a character)" );
scanf( "%d", &i );

I dont have a better idea.
 
Surprisingly little-known fact: scanf returns the number of fields it was able to read successfully. If you want to read an int and someone enters a character, that field wasn't read successfully. [tt]scanf( "%d", &i )[/tt] will return 1 if it got an int and 0 if it didn't.
 
Thanks guys for all your input. Appreciate it very much. I will all ur answers a try.

Darr
 
KeanuRocky, even the warning's required, but we still have to make some validation in the code to make a safety program.
 
/*Denniscpp:

Chipper and Newmangj are right; you can rely on the standard library functions such as scanf and atoi to do the "sanity" checking. Myself, at times, I've
preferred to write my own.

Forgive me for using my own is_digits macro instead
of using the standard "C" library, isdigit.

Regards,

Ed
*/

#include <stdio.h>


void main(int argc, char *argv[])
{
char str[50];
int x, f;

printf(&quot;enter integer string\n&quot;);
gets(str);
f=is_digit_string(str);

if(f)
{
x=atoi(str);
printf(&quot;integer is %d\n&quot;, x);
}

exit(1);
}

/*
* return true is string is all digits
*/
int is_digit_string(char *string)
{
#define is_digit(x) ((x >= '0' && x <= '9') ? 1 : 0)

while(*string)
if(!is_digit(*string++))
return(0);

return(1);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top