【发布时间】:2020-06-28 17:47:30
【问题描述】:
我仍然是 C 的初学者。我正在尝试编写一个程序来读取输入(测试用例)直到到达空行。
例如,输入如下:
2
1 2
2 5
3 6
2 3
1 7
第一个数字代表测试用例的数量。在输出中应该有每行数字的总和。 输出:
3
7
9
5
8
它们之间应该有一个空行,就像示例输出中一样。
#include <stdio.h>
typedef struct {
int a;
int b;
} A;
int main() {
int n, i = 0;
A nums[100];
scanf("%d\n", &n);
while(n--){
while(empty line not reached){
scanf("%d %d", &nums[i].a, &nums[i].b);
i++;
}
for(int j = 0; j < i; j++) printf("%d\n", nums[i].a + nums[i].b);
printf("\n");
i = 0;
}
return 0;
}
那我应该在那里写什么while(empty line not reached)我如何让程序检测到空行并转到下一个测试用例?
【问题讨论】:
-
您可以使用
fgets()测试空行,例如使用fgets(line, sizeof line, stdin); if (*line == '\n') /* deal with empty line */;。我建议您将所有scanf()替换为fgets()并更改相关代码。 -
非常感谢!!那行得通! :)
-
@Andreas 我已经解决了,谢谢:)
标签: c