Pipe an input to C++ cin from Bash
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
Related videos on Youtube
Tyler
Updated on May 25, 2022Comments
-
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 over 10 yearsWell, at least it compiled. Thats better than most on this site.
-
Chris Olsen over 10 years
-
Lee Avital over 10 yearscat "input.txt" | ./a.out > output.txt
-
WhozCraig over 10 yearsOr
./a.out < "input.txt" > "output.txt"
will likely work as well. But I use tcsh, so ymmv.
-
-
Tyler over 10 yearsThanks for the link, I did not know the difference between the two.