10

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.

4
  • 2
    Well, at least it compiled. Thats better than most on this site.
    – WhozCraig
    Oct 22, 2013 at 17:43
  • Reading piped input with C++ Oct 22, 2013 at 17:43
  • 3
    cat "input.txt" | ./a.out > output.txt
    – Lee Avital
    Oct 22, 2013 at 17:44
  • 1
    Or ./a.out < "input.txt" > "output.txt" will likely work as well. But I use tcsh, so ymmv.
    – WhozCraig
    Oct 22, 2013 at 17:46

2 Answers 2

12

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"
6

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

1
  • Thanks for the link, I did not know the difference between the two.
    – Tyler
    Oct 22, 2013 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.