作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在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/57351011/
我是一名优秀的程序员,十分优秀!