从Bash管道输入到C++ cin

Tyl*_*ler 5 c++ bash input pipe cin

我正在尝试编写一个简单的Bash脚本来编译我的C++代码,在这种情况下,它是一个非常简单的程序,它只是将输入读入一个向量,然后打印向量的内容.

C++代码:

    #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;
    }
Run Code Online (Sandbox Code Playgroud)

Bash脚本run.sh:

    #! /bin/bash

    g++ main.cpp > output.txt
Run Code Online (Sandbox Code Playgroud)

因此,编译我的C++代码并创建a.out和output.txt(由于没有输入,它是空的).我尝试了一些使用"input.txt <"的变种而没有运气.我不知道如何将我的输入文件(只是几个随机单词的简短列表)传递给我的c ++程序.

jxh*_*jxh 8

您必须首先编译该程序以创建可执行文件.然后,运行可执行文件.与脚本语言的解释器不同,g++它不解释源文件,而是编译源以创建二进制图像.

#! /bin/bash
g++ main.cpp
./a.out < "input.txt" > "output.txt"
Run Code Online (Sandbox Code Playgroud)


luk*_*uke 5

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
Run Code Online (Sandbox Code Playgroud)

Lee Avital建议正确地从文件传递输入:

cat input.txt | ./a.out > output.txt
Run Code Online (Sandbox Code Playgroud)

第一个只是重定向,而不是技术上的管道。您可能想在David Oneill此处阅读的说明:https : //askubuntu.com/questions/172982/what-is-the-difference-between-redirection-and-pipe