c - 打印标准输入中的每一行

c - print each line in stdin

我要echo "1 2\n h a\n hello" | ./a.out给我:

1 2
h a
hello

这是我当前的代码,它在一行上打印整个输入 1 2\n h a\n hello

#include <stdio.h>
#include <string.h>

int main (void)
{
    char buffer[256];

    while (fgets(buffer, sizeof(buffer), stdin)) {
        printf("%s",buffer);
    }
}

谁能帮我解决这个问题?

默认情况下,echo 不转换转义序列,因此 "\n" 实际上会发送到您的文件。见下文:

$ echo "1 2\n h a\n hello"
1 2\n h a\n hello

您可能打算这样做:

echo -e "1 2\n h a\n hello" | ./a.out

将以下内容重定向到 a.out:

1 2
 h a
 hello

如果您不想要 h ahello 之前的那些额外空格,请删除 \n 之后的空格。

-e 标志告诉 echo 转换转义序列。