Reputation: 51
I have a simple program, e.g. in C++
#include<iostream>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b;
c = a + b;
cout << c;
}
Here i need to give a
and b
as inputs at the time of execution.
I need to write a script to auto type value of a (say 5) and b (say 7) into the first terminal.
Upvotes: 0
Views: 388
Reputation: 6085
Instead of trying to write a program that interacts with multiple terminals or works with pipes, which might be more complicated, I'd recommend making your program simpler by having it handle command-line arguments. You can re-write your C++ program as follows:
#include <iostream>
#include <cstdlib> // for atoi function
using namespace std;
int main(int argc, char* argv[]) // to accept CLI inputs
{
// argv[0] has path/name to this program
// argv[1] has 1st argument, if provided
// argv[2] has 2nd argument, if provided
// if argc != 3, then we don't have everything we expected, and we bail
if(argc != 3) {
cerr << "usage: " << argv[0] << " arg1 arg2" << endl;
return -1;
}
// for simplicity, we assume that you won't get letters, only numbers
int a = atoi(argv[1]);
int b = atoi(argv[2]);
cout << (a + b);
return 0;
}
You can then write a simple shell script to launch your program with whatever arguments you want. For example, if your built program is called test
(use g++ -o test test.cpp
to build), then you can use this example launcher.bash
script:
#!/bin/bash
for i in {0..10}
do
./test $i $i
echo
done
The script produces the following output:
/tmp ❯ ./launcher.bash
0
2
4
6
8
10
12
14
16
18
20
Upvotes: 1
Reputation: 338
I think you have to change something to do so, as you want to pass the arguments from the script.
C++ program main.cpp:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc,char *argv[])
{
if(argc==1)
{
exit(1);
}
int a=atoi(argv[1]);
int b=atoi(argv[2]);
cout<<a+b<<endl;
return 0;
}
and shell script will be :
#!/bin/bash
g++ temp.cpp -o out
a=5
b=2
./out "${a}" "${b}"
You should see here for passing variables.And see this also
Upvotes: 1
Reputation: 811
If the executable is a.out then you can use
a=5;b=7;echo $a $b | ./a.out
Btw, in your example the namespace for cout/cin is missing (for e.g. add using namespace std;
after the #include).
Upvotes: 0