Validating Integer in C
-
09-07-2021 - |
Question
I am creating a program in C where i have to accept an integer to continue.I read some questions to use the following code but my program just goes into infinite loop soon after entering any character.Please help me
int tnum,scancheck;
printf("Enter the number of teams(Maximum 4)\n");
scancheck = scanf("%d",&tnum);
while(scancheck != 1)
{
printf("ERROR: Please enter numbers only\n\n");
printf("Enter the number of teams(Maximum 4)\n");
scancheck = scanf("%d",&tnum);
}
I used Kirilenko's method but my program goes into infinite loop on entering a special character such as l=
EDIT PROBLEM HAS BEEN SOLVED.Thanks guys
Solution
You have to clean stdin
between your calls to scanf
. Otherwise the behaviour of scanf
with an invalid input is to put back the character on the stream. Then, it go to an infinite loop where you read the same wrong character every iteration.
#include <stdio.h>
void clean_stdin(void) {
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
}
/* ... */
int ret;
int n;
do {
ret = scanf("%d", &n);
clean_stdin();
} while (ret != 1);
OTHER TIPS
If you wish to get an input from the user, get the line and analyze it.
char line[1024];
char * err = NULL;
int num;
while( err == NULL || *err )
{
fgets( stdin, line );
num = strtol( line, &err, 10 );
}
Until it satisfy the requirement.
Scanf puts the character back on the stdin stream if the input is invalid. Since, we are not clearing the stdin stream, it is going towards an infinite loop.
Try writing this below your scanf statement
fflush(stdin);