C: Read from stdin until Enter is pressed twice

2019-04-29 00:31发布

Consider a simple program. It must take sequences of 5 numbers from stdin and print their sums. It is not stated how many lines of input will be taken, but program must terminate if newline character is taken twice (or Enter is pressed twice).

For example,

Input:

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3/n
/n

Output:

5
10
15




#include <stdio.h>

int main()
{
    int n1, n2, n3, n4, n5;
    int sum;
    while (/*condition*/)
    {
        scanf ("%d %d %d %d %d\n", &n1, &n2, &n3, &n4, &n5);
        sum = n1 + n2 + n3 + n4 + n5;
        printf ("%d\n", sum);
    }
    return 0;
}

The only problem is I don't know what condition must be in a while-loop. A little bit of help will be appreciated.

Thanks in advance.

标签: c io stdin
2条回答
时光不老,我们不散
2楼-- · 2019-04-29 01:09

Use getc(stdin) (man page) to read a single character from stdin, if it isn't a newline you can put it back with ungetc(ch, stdin) (man page) and use scanf to read your number.

int main() {
    int sum = 0;
    int newlines = 0;
    int n = 0;
    while(1) {
        int ch = getc(stdin);
        if(ch == EOF) break;
        if(ch == '\n') {
            newlines++;
            if(newlines >= 2) break;
            continue;
        }

        newlines = 0;
        ungetc(ch, stdin);
        int x;
        if(scanf("%d", &x) == EOF) break;
        sum += x;
        n++;
        if(n == 5) {
            printf("Sum is %d\n", sum);
            n = 0;
            sum = 0;
        }
    }
}

Online demo: http://ideone.com/y99Ns6

查看更多
唯我独甜
3楼-- · 2019-04-29 01:10

Well, you could simply put the scanf call in the condition, and check if it succeeded in setting your variables.

#include <stdio.h>

int main()
{
    int n1, n2, n3, n4. n5;
    int sum;
    while (scanf ("%d %d %d %d %d\n", n1, n2, n3, n4, n5) != EOF)
    {
        sum = n1 + n2 + n3 + n4 + n5;
        printf ("%d\n", sum);
    }
    return 0;
}

(Couldn't test this code myself)

查看更多
登录 后发表回答