gpt4 book ai didi

c - 如何在 C 程序中的 char 数组中分配输入(来自 echo 命令)

转载 作者:行者123 更新时间:2023-11-30 16:14:55 25 4
gpt4 key购买 nike

如何在C程序中将echo的输入分配到char数组中?例如:

$ echo "Hello, world!" | ./hello

我需要将字符串“Hello, world”保存到数组中。

最佳答案

echo 的输出是 pipedhello 的输入。要在 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/57351011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com