我想解析如下输入:
1 2 3\n4 5 6\n7 8 9\n\n
并且对于每一行,将每个值保存在 int ant 中,并将其打印到标准输出,直到我得到一个空行,所以对于这个例子,我会得到:
1 2 3
1 2 3
4 5 6
4 5 6
7 8 9
7 8 9
我试过类似的东西
int n1, n2, n3;
while(scanf ("%d %d %d\n", n1, n2, n3) != EOF) {
printf("%d %d %d\n", n1, n2, n3);
fflush(stdout);
}
但是好像不行。有什么简单的方法可以做到这一点吗?
最佳答案
scanf
无法实现您正在尝试做的事情,因为它会一直读取直到满足条件,并且 %d
说明符将忽略 '\n'
换行符,我推荐这段代码
#include <stdio.h>
#include <string.h>
int main()
{
int n1, n2, n3;
char line[64];
/* read at least 63 characters or unitl newline charater is encountered with */
/* fgets(line, sizeof line, stdin) */
/* if the first character is a newline, then it's an empty line of input */
while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n'))
{
/* parse the read line with sscanf */
if (sscanf(line, "%d%d%d", &n1, &n2, &n3) == 3)
{
printf("%d %d %d\n", n1, n2, n3);
fflush(stdout);
}
}
return 0;
}
虽然此代码有效,但它并不健壮,因为在下面 WhozCraig 评论的情况下它会失败,所以这是一种可以让您远离问题的方法
#include <stdio.h>
#include <string.h>
#include <ctype.h> /* for isspace */
int isEmpty(const char *line)
{
/* check if the string consists only of spaces. */
while (*line != '\0')
{
if (isspace(*line) == 0)
return 0;
line++;
}
return 1;
}
int main()
{
int n1, n2, n3;
char line[64];
while ((fgets(line, sizeof line, stdin) != NULL) && (isEmpty(line) == 0))
{
if (sscanf(line, "%d%d%d", &n1, &n2, &n3) == 3)
{
printf("%d %d %d\n", n1, n2, n3);
fflush(stdout);
}
}
return 0;
}
关于c - 从标准输入读取输入直到空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27607744/