我想要 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 a
之前有那些额外的空格和 hello
, 去掉 \n
后面的空格的。
-e
flag 告诉 echo 转换转义序列。
关于c - 打印标准输入中的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37892676/