What happens when you type things like 12ab in scanf ("% d", & arg)?

I ran into this problem when I want to check what I entered, a number. The scanf function will return 1 if I successfully cite a number. So here is what I wrote:

int argu;
while(scanf("%d",&argu)!=1){
    printf("Please input a number!\n");
}

But when I introduced things like abcd into it, the loop would go on forever and not stop for a hint.

I looked it up on the Internet and found that it has something to do with the cache, and I need to clear it, so scanf can get new data. So I tried fflush, but that didn't work.

Then I saw this:

int argu,j;
while(scanf("%d",&argu)!=1){
    printf("Please input a number!\n");
    while((j=getchar())!='\n' && j != '\n');
}

Then, when I introduced things like "abcd", it worked well and it requested my data. But when I introduced things like "12ab", this would not work again.

, scanf ( "% d", & arg) , ?

, while(*eptr != '\n').

, fgets '\n' , fget - . .

+5
5

, fgets(), , " " .

.

fgets(), strtol(), , , .

:

char line[128];

while(fgets(line, sizeof line, stdin) != NULL)
{
   char *eptr = NULL;
   long v = strtol(line, &eptr, 10);
   if(eptr == NULL || !isspace(*eptr))
   {
     printf("Invalid input: %s", line);
     continue;
   }
   /* Put desired processing code here. */
}
+4

, abcd, .

, scanf , , . , , scanf a , , %d, . . . . .

fflush , .

"12ab", scanf "12", "ab" .

, strtol ( ) strtod ( ). :

char input[SIZE]; // assume SIZE is big enough for whatever input we get
int value;

if (fgets(input, sizeof input, stdin) != NULL)
{
  char *chk;
  int tmp = (int) strtol(input, &chk, 10);
  if (isspace(*chk) || *chk == 0)
    value = tmp;
  else
    printf("%s is not a valid integer string\n", input);
}

chk , . 0, . , "12ab", "abcd".

scanf , , . , , fgets .

+2

I suggest entering the input as a string and checking for numeric characters. If the input is valid, convert the string to int with the help sscanf(str,"%d",&i);or error diplay.

+1
source

Just call scanf ("% * [^ \ n] \ n") inside the loop and drop the "cache".

+1
source

Call scanf("%*[^\n]\n")inside the loop. This should be enough to drop everything related to the cache.

0
source

All Articles