How do you read scanf until EOF in C?

前端 未结 7 2104
暗喜
暗喜 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:12

    Try:

    while(scanf("%15s", words) != EOF)
    

    You need to compare scanf output with EOF

    Since you are specifying a width of 15 in the format string, you'll read at most 15 char. So the words char array should be of size 16 ( 15 +1 for null char). So declare it as:

    char words[16];
    
    0 讨论(0)
  • 2020-12-03 03:16

    Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):

    Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

    0 讨论(0)
  • 2020-12-03 03:20

    You need to check the return value against EOF, not against 1.

    Note that in your example, you also used two different variable names, words and word, only declared words, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NUL character.

    0 讨论(0)
  • 2020-12-03 03:22

    For C users, this will also work

    while ( gets(str) != NULL )
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-03 03:35

    I guess best way to do this is ...

    int main()
    {
        char str[100];
        scanf("[^EOF]",str);
        printf("%s",str);
        return 0;     
    }
    
    0 讨论(0)
提交回复
热议问题