How do you read scanf until EOF in C?

前端 未结 7 2105
暗喜
暗喜 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:36

    Scanf is pretty much always more trouble than it's worth. Here are two better ways to do what you're trying to do. This first one is a more-or-less direct translation of your code. It's longer, but you can look at it and see clearly what it does, unlike with scanf.

    #include <stdio.h>
    #include <ctype.h>
    int main(void)
    {
        char buf[1024], *p, *q;
        while (fgets(buf, 1024, stdin))
        {
            p = buf;
            while (*p)
            {
                while (*p && isspace(*p)) p++;
                q = p;
                while (*q && !isspace(*q)) q++;
                *q = '\0';
                if (p != q)
                    puts(p);
                p = q;
            }
        }
        return 0;
    }
    

    And here's another version. It's a little harder to see what this does by inspection, but it does not break if a line is longer than 1024 characters, so it's the code I would use in production. (Well, really what I would use in production is tr -s '[:space:]' '\n', but this is how you implement something like that.)

    #include <stdio.h>
    #include <ctype.h>
    int main(void)
    {
        int ch, lastch = '\0';
        while ((ch = getchar()) != EOF)
        {
            if (!isspace(ch))
                putchar(ch);
            if (!isspace(lastch))
                putchar('\n');
            lastch = ch;
        }
        if (lastch != '\0' && !isspace(lastch))
            putchar('\n');
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题