【问题标题】:C: Read from stdin until Enter is pressed twiceC:从标准输入读取,直到按两次 Enter
【发布时间】:2013-03-16 04:00:06
【问题描述】:

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

例如,

输入:

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

唯一的问题是我不知道while循环中必须有什么条件。我们将不胜感激。

提前致谢。

【问题讨论】:

  • 你的scanf错了应该是scanf ("%d %d %d %d %d\n", &amp;n1, &amp;n2, &amp;n3, &amp;n4, &amp;n5)
  • 数字必须分行吗?
  • @MohamedKALLEL 谢谢,我已经编辑了问题
  • @teppic 是的,他们必须

标签: c io stdin


【解决方案1】:

使用getc(stdin) (man page) 从stdin 读取单个字符,如果它不是换行符,您可以使用ungetc(ch, stdin) (man page) 将其放回原处并使用scanf 读取你的号码。

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

【讨论】:

  • 好答案。一件事:ch 应该是一个 int,以便测试 EOF。
  • "如果 (n == 5) 中断;"这行不会在取 5 个数字后打破循环吗?
  • @KudayarPirimbaev 没错。我就是这样理解你的问题的;如果它不是您想要的,只需将其删除(以及n 的声明,以及最后n 的打印。)
  • 啊,谢谢,关键是它必须打印所有序列的所有总和,直到按两次 Enter,编辑问题
  • 这种情况下if(n == 5)后面的break可以换成{ printf("Sum is %d\n", sum); sum = n = 0; }
【解决方案2】:

好吧,您可以简单地将 scanf 调用放在条件中,并检查它是否成功设置了您的变量。

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

(无法自己测试此代码)

【讨论】:

  • 谢谢,我还有一个问题:如果我不知道要取多少个数字,我该怎么办?关键是我的程序必须采用与以下属性相对应的线条:第一个数字是图形的形状,1 - 圆形,2 - 矩形,然后是坐标(中心和半径的坐标与角的 4 个坐标)。我的程序必须将所有区域相加,忽略重叠等。在这种情况下我该怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多