【问题标题】:How to assign input (from echo command) in char array in C program [closed]如何在 C 程序的 char 数组中分配输入(来自 echo 命令)[关闭]
【发布时间】:2016-10-16 19:04:46
【问题描述】:

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

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

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

【问题讨论】:

标签: c


【解决方案1】:

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!"
$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2013-07-06
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多