Fgets instructions are skipped. Why?

Whenever I do scanf before fgets, the fgets statement is skipped. I ran into this problem in C ++ and I remember that I had some kind of intuition that would clear the stdin buffer or something like that. I suggest that there is an equivalent to C. What is it?

Thanks.

+4
source share
2 answers

I bet because \ n is stuck in the input stream.

See one of the following questions:

I can not clear stdin.
How do I make Flushing STDIN here? scanf () calls an infinite loop

or this answer .

Also: Why not use scanf () .

PS fgets() is a function, not an instruction.

+5
source

The fgets() function following the scanf() call probably cannot be skipped 1 . This is probably 1 returning immediately, finding a new line in the input stream.

Calling scanf() before fgets() almost always causes scanf() leave an unused newline ( '\n' ) line in the input stream, which is what fgets() looks like.

To mix scanf() and fgets() , you need to remove the new line left by calling scanf() from the input stream.

One solution for flushing stdin (including a new line) would be something like the following:

 int c; /* discard all characters up to and including newline */ while ((c = getchar()) != '\n' && c != EOF); 

1 - It is difficult to be sure without seeing the actual code.


Or, as Jerry Coffin said in his comment below, you can use scanf("%*[^\n]"); . The directive "%*[^\n]" indicates scanf() to match those that are not newlines, and suppress the purpose of the conversion result.

 /* match up to newline */ scanf("%*[^\n]"); /* discard the newline */ scanf("%*c"); 

From http://c-faq.com/stdio/gets_flush1.html :

The initial scanf() with "%*[^\n]" will either consume everything before, but not include a new line, or crash. The subsequent "%*c" (or plain old getchar() ) will use the newline, if any.

This last โ€œifโ€ matters: the user may have signaled EOF. In this case, getchar() or scanf("%*c") can - this decision is left by people who write your compiler, either immediately return EOF, or return to the user for more input. If developers choose the latter, the user may need to click โ€œstop this thingโ€ (^ D, ^ Z, mouse button, front panel switch, or something else) for extra time. It is annoying if nothing else.


Or, as Chris Dodd suggested in his comment below, you can use scanf("%*[^\n]%*1[\n]"); . The directive "%*[^\n]%*1[\n]" tells scanf() to match those that are not newline characters, and then match one newline and suppress the purpose of the conversion results.

 /* match and discard all characters up to and including newline */ scanf("%*[^\n]%*1[\n]"); 
+3
source

Source: https://habr.com/ru/post/1310881/


All Articles