Reputation: 31
I'm having trouble with the following code, when I enter a letter isdigit won't detect it and I get the error message "Nothing entered"
int age;
char buffer[100] = "";
printf("Enter your age: ");
fgets(buffer, 100, stdin);
age = atoi(buffer);
printf("%d\n",age);
if (age == NULL)
{
printf("Nothing entered\n");
}
else if (isdigit(age) == 0)
{
printf("Not a number\n");
}
else if (age <1 || age > 110)
{
printf("Out of range\n");
}
else
{
printf("Thank you\n");
}
Upvotes: 0
Views: 180
Reputation: 206567
Instead of
age = atoi(buffer);
printf("%d\n",age);
if (age == NULL)
{
printf("Nothing entered\n");
}
Use
if ( sscanf(buffer, "%d", &age) != 1 )
{
printf("Nothing entered\n");
}
else
{
printf("%d entered\n", age);
}
Upvotes: 2
Reputation: 50110
explanation of the behavior
atoi("x")
will return 0. This is becuase atoi stops on the first non digit
if (age == NULL)
is then true because NULL is defined as 0 (basically)
You should check buffer first and then do atoi
Upvotes: 0
Reputation: 9343
atoi
is the wrong function to use when you have untrusted/potentially erroneous input (i. e. almost always).
Use strtol()
(man page) instead, which allows for extensive error checking.
Also, do check the return value of fgets()
.
char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
char *end;
errno = 0;
long n = strtol(buf, &end, 10);
// check for errors
if (n == 0 || n == LONG_MIN || n == LONG_MAX) {
if (errno != 0) {
printf("Erroneous input entered\n");
} else {
// process valid input
}
} else {
// process valid input
}
} else {
printf("nothing was entered\n");
}
By the way, it doesn't make sense to compare an int
with NULL
(which is a pointer). If this doesn't trigger at least a compiler warning (better yet, a hard error), you need to boost your compiler warning level or change to a modern compiler.
Upvotes: 2