Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe an input to C++ cin from Bash

I'm trying to write a simple Bash script to compile my C++ code, in this case it's a very simple program that just reads input into a vector and then prints the content of the vector.

C++ code:

    #include <string>
    #include <iostream>
    #include <vector>

    using namespace std;

    int main()
    {
         vector<string> v;
         string s;

        while (cin >> s)
        v.push_back(s);

        for (int i = 0; i != v.size(); ++i)
        cout << v[i] << endl;
    }

Bash script run.sh:

    #! /bin/bash

    g++ main.cpp > output.txt

So that compiles my C++ code and creates a.out and output.txt (which is empty because there is no input). I tried a few variations using "input.txt <" with no luck. I'm not sure how to pipe my input file (just short list of a few random words) to cin of my c++ program.

like image 577
Tyler Avatar asked Oct 22 '13 17:10

Tyler


2 Answers

You have to first compile the program to create an executable. Then, you run the executable. Unlike a scripting language's interpreter, g++ does not interpret the source file, but compiles the source to create binary images.

#! /bin/bash
g++ main.cpp
./a.out < "input.txt" > "output.txt"
like image 81
jxh Avatar answered Nov 15 '22 15:11

jxh


g++ main.cpp compiles it, the compiled program is then called 'a.out' (g++'s default output name). But why are you getting the output of the compiler? I think what you want to do is something like this:

#! /bin/bash

# Compile to a.out
g++ main.cpp -o a.out

# Then run the program with input.txt redirected
# to stdin and the stdout redirected to output.txt
./a.out < input.txt > output.txt

Also as Lee Avital suggested to properly pipe an input from the file:

cat input.txt | ./a.out > output.txt

The first just redirects, not technically piping. You may like to read David Oneill's explanation here: https://askubuntu.com/questions/172982/what-is-the-difference-between-redirection-and-pipe

like image 38
luke Avatar answered Nov 15 '22 17:11

luke