C:从stdin读取,直到按两次Enter键 [英] C: Read from stdin until Enter is pressed twice

查看:162
本文介绍了C:从stdin读取,直到按两次Enter键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个简单的程序。它必须从stdin中获取5个数字的序列并打印它们的总和。没有说明将输入多少行,但如果换行字符被取两次(或按两次Enter键),程序必须终止。

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).

例如,

输入:

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

输出:

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.

提前致谢。

推荐答案

使用 getc(stdin)手册页)从 stdin 中读取单个字符,如果它不是换行符,你可以用将其放回去ungetc(ch,stdin)手册页)并使用 scanf 来读取您的号码。

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;
        }
    }
}

在线演示: http://ideone.com/y99Ns6

这篇关于C:从stdin读取,直到按两次Enter键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆