Why does scanf not work properly sometimes

[c] scanf () is skipped (c-beginner)

heat said:

If I go after that I would have 1 character and the '\ 0' in other words a length of 2. I tried that too and I get the same error as with scanf () from earlier ^^.

Click to enlarge ...

This is because fgets leaves the rest of the line in the input stream if the given number of characters has already been read. If you use 2 here, this is what happens:

  • For example, the user enters a and presses return.
  • In the input stream there are now the characters "a \ n" (the \ n is the line break).
  • fgets (old, 2, stdin) reads the a, notices that it cannot read any more characters because of the zero termination and writes "a \ 0" in old. "\ N" remains in the input stream.
  • fgets (new, 2, stdin) reads the \ n and recognizes it as the end of the line. It rewrites "\ n \ 0" in.

But even with 3 you get the same problem if the user enters more than one character. You are on the safe side if you remove the remaining line from the input stream after each entry. You can use the following function, for example:


Your main could then look like this:


Ideally, you should also catch possible errors, i.e. test the return values ​​from fgets, getchar and ignore_line.

Uncle Schuppig said:

At Microsoft, the end of the line is even 2 characters long: carriage return + line feed. But fgets () stops reading in the CR and appends a 0 to the end. That is why you need 3 characters for one letter.

Click to enlarge ...

That is not completely right. fgetsstops when it sees an LF ('\ n') in the input stream. And even under Windows you only get an LF and no CRLF when the user presses Return.