-2

How to assign input of echo in char array in C program? For example:

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

I need to save string "Hello, world" to an array.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • [getline](http://linux.die.net/man/3/getline). – zwol Oct 16 '16 at 19:05
  • read from stdin. See [this question](http://stackoverflow.com/questions/15883568/reading-from-stdin). – Catweazle Oct 16 '16 at 19:09
  • 1
    @Catweazle: that question is about using the `read()` system call, which is certainly doable, but not necessary. There are ways to do it using the standard I/O library (``) that are probably more appropriate at this stage. – Jonathan Leffler Oct 16 '16 at 19:49
  • Please read "[ask]", "[mcve]" and “[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/q/261592)”. We need to see your attempt at solving this along with why that didn't work. Without that it looks like you want us to write the code for you. – the Tin Man Oct 16 '16 at 20:02

1 Answers1

1

The output of echo is piped to the input of hello. To get a string as an input in C, use fgets: http://www.cplusplus.com/reference/cstdio/fgets/. Here is some example code:

hello.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 is Tim's post about his code

Shell command:

$ gcc hello.c
$ echo "Hello, world!" | ./a.out
Value of inputarr: "Hello, world!"
$
Community
  • 1
  • 1
K Zhang
  • 269
  • 3
  • 9