Pipe an input to C++ cin from Bash

Tyler picture Tyler · Oct 22, 2013 · Viewed 13.9k times · Source

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.

Answer

jxh picture jxh · Oct 22, 2013

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"