Pipe an input to C++ cin from Bash

15,534

Solution 1

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"

Solution 2

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

Share:
15,534

Related videos on Youtube

Tyler
Author by

Tyler

Updated on May 25, 2022

Comments

  • Tyler
    Tyler almost 2 years

    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.

    • WhozCraig
      WhozCraig over 10 years
      Well, at least it compiled. Thats better than most on this site.
    • Chris Olsen
      Chris Olsen over 10 years
    • Lee Avital
      Lee Avital over 10 years
      cat "input.txt" | ./a.out > output.txt
    • WhozCraig
      WhozCraig over 10 years
      Or ./a.out < "input.txt" > "output.txt" will likely work as well. But I use tcsh, so ymmv.
  • Tyler
    Tyler over 10 years
    Thanks for the link, I did not know the difference between the two.