Mapleman
Mapleman

Reputation: 45

Write a shell script that runs an program that requires input with cin

In detail, I wrote a shell snippet, like this:

while read input
do
  ./a.out
done < "$1"

"$1" is test file with several rows. Each row is one test case.

a.out is compiled C++ file which my test cases run against. The C++ source code is like this:

while (1) {
  cout << "Enter:\n"
  if ((cin >> v1) && (cin >> v2)) {
    cout << v1 << "\n";
    cout << v2 << "\n";
  }
}

We are not allowed to make a.out take parameters like this: ./a.out [parameters]

For example, the test file contains two test cases:

"a b"
"c d"

What I expect is, after running over my script,

a
b
c
d

should be output. Thanks

Upvotes: 1

Views: 3963

Answers (3)

txipi
txipi

Reputation: 141

If your C++ program needs some kind of text-based interactive interaction, expect might be a good choice (see http://linux.die.net/man/1/expect).

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74685

Say that your full code was this:

#include <iostream>

int main() {
    int v1, v2;
    std::cin >> v1;
    std::cin >> v2;
    std::cout << "v1: " << v1 << " v2: " << v2 << "\n";
    return 0;
}

If the file that you are reading in your script has lines that look like this:

4 5
6 7

Then the loop in your shell script loop could be written like this:

while read input
do
    echo "$input" | ./a.out
done < "$1"

Running your shell script like ./script.sh file would give the following output:

v1: 4 v2: 5
v1: 6 v2: 7

Upvotes: 2

here documents might help. They can contain variables, and you could fill them.

Read also advanced bash scripting guide

If your a.out can process a single line, try also pipes like

echo $A $B | a.out

or maybe use printf(1) instead of echo above

Upvotes: 0

Related Questions