通过管道将输入从 Bash 传输到 C++ cin 中

Pipe an input to C++ cin from Bash

本文关键字:传输 C++ cin Bash 管道 输入      更新时间:2023-10-16

我正在尝试编写一个简单的 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;
    }

Bash 脚本 run.sh:

    #! /bin/bash
    g++ main.cpp > output.txt

因此,这将编译我的C++代码并创建 a.out 和输出.txt(由于没有输入,因此为空)。我尝试了一些使用"input.txt <"的变体,但没有运气。我不确定如何将我的输入文件(只是几个随机单词的简短列表)通过管道传输到我的 c++ 程序的 cin。

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

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

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