I was trying to scan only allowed types in my c program.
I have a variable which is integer.I want to scan again while user input is character.
int usercount;
do{
printf("enter user count");
scanf("%d",&usercount);
}
while(!isdigit(usercount));
But when input is char it’s in a infinite loop.Can anyone help?
The
scanf()function has a return value. It tells you how many “conversions” it succeeded in doing. In this case, it will return 0 if failed to interpret the input as an integer. Your code should inspect the return value.In general, to be less sensitive with “stuff” left in the buffered input queue, you should read a full line at a time with
fgets(), and then usesscanf()(or any other parsing function, likestrtoul()) to parse the data.