1

I have a c++ code which requires an input value. I would like to have a bash script to run my c++ executable file automatically. My bash script is below:

#!/bin/bash
g++ freshness.cpp -g -o prob
for((i=0;i<30;i++))
{
    ./prob<$2 ../../data/new_r.txt ../../data/new_p.txt ../../data  /t_$1.txt  >> result.txt
}
./cal result.txt
rm result.txt

My main.cpp is below:

int main(int argc,char*argv[])
{
    map<int, struct Router> nodes;
    cout<<"creating routers..."<<endl;
    Create_router(argv[1],nodes);
    cout<<"creating topology..."<<endl;
    LoadRouting(argv[2],nodes);
    cout<<"simulating..."<<endl;
    Simulate(argv[3],nodes);
    return 0;
}

There is a cin in Create_router(argv[1],nodes), like cin>>r_size;

Many thanks in advance.

4
  • Is there an actual question here? Commented Sep 8, 2017 at 19:12
  • My bash script doesn't work. I don't know how to pass an input value from a bash script to a c++ executable file Commented Sep 8, 2017 at 19:28
  • @JaysonZhang, how are invoking the bash script? Commented Sep 8, 2017 at 19:33
  • Your script is using $2 as the name of the file to get the program's input from. Is that what you want? If not, what do you really want? Commented Sep 8, 2017 at 19:34

1 Answer 1

2
./prob < $2

means to redirect the input of the program to a file whose name is in the $2 variable.

If $2 is the actual input data, not a filename, then you should use a here-string:

./prob <<< "$2" ../../data/new_r.txt ../../data/new_p.txt ../../data  /t_$1.txt  >> result.txt

or a here-doc:

./prob <EOF ../../data/new_r.txt ../../data/new_p.txt ../../data  /t_$1.txt  >> result.txt
$2
EOF

or pipe the input to the program:

printf "%s\n" "$2" | ./prob ../../data/new_r.txt ../../data/new_p.txt ../../data  /t_$1.txt  >> result.txt

The here-string method is the simplest, but it's a bash extension. The other methods are portable to all POSIX shells.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.