Detecting EOF in C

后端 未结 6 952
猫巷女王i
猫巷女王i 2020-12-16 10:07

I am using the following C code to take input from user until EOF occurs, but problem is this code is not working, it terminates after taking first input. Can anyone tell me

6条回答
  •  余生分开走
    2020-12-16 10:43

    EOF is just a macro with a value (usually -1). You have to test something against EOF, such as the result of a getchar() call.

    One way to test for the end of a stream is with the feof function.

    if (feof(stdin))
    

    Note, that the 'end of stream' state will only be set after a failed read.

    In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.

提交回复
热议问题