考虑一个简单的程序。它必须从 stdin 获取 5 个数字的序列并打印它们的和。没有说明将采用多少行输入,但如果换行符被采用两次(或按两次 Enter 键),则程序必须终止。
例如,
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;
}
唯一的问题是我不知道 while 循环中必须满足什么条件。如果有一点帮助,我们将不胜感激。
提前致谢。
Use getc(stdin)
(man page http://pubs.opengroup.org/onlinepubs/007908799/xsh/fgetc.html) 读取单个字符stdin
,如果它不是换行符,您可以将其放回原处ungetc(ch, stdin)
(man page http://pubs.opengroup.org/onlinepubs/007908799/xsh/ungetc.html)并使用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 http://ideone.com/y99Ns6
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)