How fget works?

后端 未结 4 1930
傲寒
傲寒 2021-01-23 15:31

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

4条回答
  •  -上瘾入骨i
    2021-01-23 15:59

    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):

    1. Use fgets() to get the first input, then parse it using strtol() to get T.

    2. Add an extra fgets() after the scanf().

    3. 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.

    4. 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.

提交回复
热议问题