How do you read scanf until EOF in C?

前端 未结 7 2138
暗喜
暗喜 2020-12-03 02:56

I have this but once it reaches the supposed EOF it just repeats the loop and scanf again.

int main(void)
{
        char words[16];

        while(scanf(\"%1         


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 03:30

    Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:

    if (scanf("%15s", word) == 1)
        printf("%s\n", word);
    

    If you want to loop as long as you can read a word, use while:

    while (scanf("%15s", word) == 1)
        printf("%s\n", word);
    

    Also, as others have noted, you need to give the word array a size that is big enough for your scanf:

    char word[16];
    

    Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.

    edit

    Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David

提交回复
热议问题