How fget works?

后端 未结 4 1927
傲寒
傲寒 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条回答
  •  礼貌的吻别
    2021-01-23 15:58

    With your first call to scanf you allow the user to input an integer for the number of loops. They do so, and use a carriage return to signal the end of input. At this point scanf reads the integer, but leaves the end-of-line (\n) in the stream..

    So when you call fgets, fgets gets from the stream until it reaches the first newline -- in you code, on the first loop, this is the very first character it encounters.

    If you discard the newline before calling fgets, you should get your desired results. You can do this, for example by changing your first three lines to:

        int T;
        char newline;
        scanf("%d%c",&T, &newline);
    

    Although there are probably stylistically superior ways of doing this.

提交回复
热议问题