fgets() does not work as I expect it to

后端 未结 3 1612
逝去的感伤
逝去的感伤 2021-01-19 17:17

Can anyone tell me why this code does not work? When i run, it just prints out \"Enter info about trail 1\" and without any input, skips to another step.

#in         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 17:58

    Issue

    The scanf function in main reads the integer, but leaves the newline \n on the input stream. When the first loop iteration of readingArrays comes around, fgets sees this newline and assumes you have already entered your trail info and pressed enter. It prints the empty string and newline, and goes on to the next iteration.

    Solution

    One solution would be to tell scanf to read and ignore whitespace after the digit by adding a space after %d format specifier.

    So to get numberOfTrails from stdin, you would do

    scanf("%d ",&numberOfTrails);
    

    Thanks to @Ray for pointing out this solution!

提交回复
热议问题