Login for C ++ cin from Bash

I am trying to write a simple Bash script to compile my C ++ code, in this case it is a very simple program that just reads the input into the vector and then prints the contents 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 it compiles my C ++ code and creates a.out and output.txt (which is empty because there is no input). I tried several options using "input.txt <" with no luck. I'm not sure how to pass my input file (just a short list of a few random words) to the cin of my C ++ program.

+4
source share
2 answers

. . , g++ , .

#! /bin/bash
g++ main.cpp
./a.out < "input.txt" > "output.txt"
+6

g++ main.cpp , "a.out" ( g++). ? , - :

#! /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

, Lee Avital :

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

, . David Oneill : https://askubuntu.com/questions/172982/what-is-the-difference-between-redirection-and-pipe

+4

All Articles