C: Read from stdin until Enter is pressed twice

时光怂恿深爱的人放手 提交于 2019-12-05 07:59:48
Jacob Parker

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

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!