For example, when you want to get input from user in Java, you simply use Scanner in = new Scanner
, now I want to get input from user which is gonna input using echo command, such as echo 2 3 | sh addition
, what C commands do I put in my script so that it reads the 2 and 3? Thanks!

- 29
- 5
-
Step one is to learn the language. Here's a [list of books](http://stackoverflow.com/a/562377/3386109) to help you get started. – user3386109 Feb 05 '16 at 04:27
2 Answers
C
echo 2 3 | sh addition
basicially means "input 2
, a space and 3
into the command sh addition
", which means you should be able to read 2
and 3
in your program as it is manually typed in.
However, sh addition
means excuting a shell script which is not C. A C program could be excuted directly with its file name, i.e. ./a.out
where a.out
is your program. So the following program:
#include <stdio.h>
int main () {
int a, b;
scanf("%d %d", &a, &b);
printf("%d + %d = %d\n", a, b, a+b);
return 0;
}
Should do what you want. After you compile it to a excutable, for example a.out
, you can run it by
echo 2 3 | ./a.out
Shell script
sh addition
means run a shell script. To write a shell script you write something like this in a file named addition
which you will be able to run using sh addition
or echo 1 2 | sh addition
.
#!/bin/sh
read a b # read two int, one put in a and another put in b.
echo -n "$a + $b = ";
expr $a + $b
read
is just like scanf
, and expr
do calculation and output.

- 1,982
- 1
- 18
- 22
-
hmm thanks, i thought writing in vim is the same as c.. if I want to do `sh filename`, what do I need to modify? thanks again. – P7GAB Feb 05 '16 at 04:53
I guess you meant "what C instructions should I use in my C program to read standard input"...Ok?
Well... you can use several instructions to read your standard input. I guess you might want to start using scanf(). Something like this:
... all includes, declarations, etc. here ...
scanf ( "%d %d", &a, &b ) ;
// a and b are the two integer variables where you will store 2 and 3
...

- 5,730
- 2
- 26
- 25
-
i thought writing in vim is the same as c.. if I want to do sh filename, what do I need to modify? thanks again! – P7GAB Feb 05 '16 at 04:53
-
I do not understand. Vim is an editor. C is a programming language and shell is a totally different stuff. – mauro Feb 05 '16 at 04:57