I am using gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
I am writing a very simple script to take string as input and print the same with the some custom message. Fi
This is because your scanf()
call
scanf("%d",&T);
does not consume the new line character \n
accompanied by your input.
When you input T
, your input is 2Enter.
scanf()
consumes the 2
, sees \n
and stops consuming, leaving \n
in the input buffer.
When the fgets()
gets called, it sees the \n
in the buffer and treats this as the input.
To solve this, you have a few choices (in decreasing order of my subjective preference):
Use fgets()
to get the first input, then parse it using strtol()
to get T
.
Add an extra fgets()
after the scanf()
.
Add getchar()
to consume one extra character. This works if you are certain that exactly one \n
will be present after the input. So for example it won't work if you type 2SpaceEnter. Alternatively, you may use while(getchar() != '\n');
after the scanf()
to consume everything up to a new line, but this may cause problems if an empty line is a valid input to your later fgets()
calls.
If your implementation supports it, you may use fpurge(stdin)
or __fpurge(stdin)
.
And, very importantly, do not use fflush(stdin)
unless your implementation clearly defines its behavior. Otherwise it is undefined behavior. You may refer to this question for more details. Also, note that the fpurge()
and fflush()
methods may not work correctly if your input can be piped into the program.