【问题标题】:Pipe an input to C++ cin from Bash从 Bash 管道输入到 C++ cin
【发布时间】:2013-10-31 17:28:15
【问题描述】:

我正在尝试编写一个简单的 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 脚本运行.sh:

    #! /bin/bash

    g++ main.cpp > output.txt

这样就可以编译我的 C++ 代码并创建 a.out 和 output.txt(因为没有输入,所以它是空的)。我使用“input.txt

【问题讨论】:

  • 好吧,至少它编译好了。这比这个网站上的大多数都好。
  • cat "input.txt" | ./a.out > output.txt
  • ./a.out &lt; "input.txt" &gt; "output.txt" 也可能会起作用。但是我用的是tcsh,所以ymmv。

标签: c++ bash input pipe cin


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • 感谢链接,我不知道两者的区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多