如何在C程序中将echo的输入分配到char数组中? 例如:
$ echo "Hello, world!" | ./hello
我需要将字符串“Hello, world”保存到数组中。
最佳答案
echo 的输出是 piped到 hello
的输入。要在 C 中获取字符串作为输入,请使用 fgets
:http://www.cplusplus.com/reference/cstdio/fgets/ 。这是一些示例代码:
你好.c:
#include <stdio.h>
#include <string.h>
int main() {
char inputarr[256];
fgets(inputarr, 256, stdin);
//Credit to Tim Čas for the following code to remove the trailing newline
inputarr[strcspn(inputarr, "\n")] = 0;
printf("Value of inputarr: \"%s\"\n", inputarr);
}
Here是 Tim 关于他的代码的帖子
外壳命令:
$ gcc hello.c
$ echo "Hello, world!" | ./a.out
Value of inputarr: "Hello, world!"
$
关于c - 如何在 C 程序中的 char 数组中分配输入(来自 echo 命令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074282/