从 Bash 管道输入到 C++ cin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19524723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:22:50  来源:igfitidea点击:

Pipe an input to C++ cin from Bash

c++bashinputpipecin

提问by Tyler

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.

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

C++ code:

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;
    }

Bash script run.sh:

Bash 脚本 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.

这样就编译了我的 C++ 代码并创建了 a.out 和 output.txt(它是空的,因为没有输入)。我使用“input.txt <”尝试了一些变体,但没有成功。我不确定如何将我的输入文件(只是一些随机单词的简短列表)通过管道传输到我的 C++ 程序的 cin。

回答by jxh

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.

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

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

回答by luke

g++ main.cppcompiles 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:

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

Also as Lee Avitalsuggested to properly pipe an input from the file:

同样Lee Avital建议从文件中正确管道输入:

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

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