c - 从标准输入读取输入直到空行

标签 c parsing input stdin scanf

我想解析如下输入:

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/

相关文章:

c++ - 在 CUDA 中有这样的可能吗

c - C 程序中的链接器错误 : LNK2019 and LNK1120

PHP 以数组格式从 PDF 中提取数据

javascript - 如何将输入文本字段中的一些文本设为粗体?

java - 一次读入文本文件 1 行并将单词拆分为 Array Java

c - 我将如何在这里应用余数/模运算符?

无法在 C 中使用 system() 函数执行 "cat"

parsing - 为什么有些编译器更喜欢手工制作的解析器而不是解析器生成器?

php - 需要 Laravel 移动应用程序的推送服务

c++ - 输入到文本文件