通过管道将输入从 Bash 传输到 C++ cin 中
Pipe an input to C++ cin from Bash
我正在尝试编写一个简单的 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
相关文章:
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- Angelscript从C++传输数组
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 从服务器传输到客户端的消息不会出现
- USB传输的LibUSB C++格式不同
- 在本地网络中通过OpenCV(C++)实时流式传输图像
- 将相机数据从服务器实时流式传输到客户端
- 加密在 Windows、C++ 和 Java 中传输中的数据
- 如何从网站获取数据并将其传输到数据库?
- 使用蓝牙组件将数据从Android手机传输到串行设备时出现问题
- 在 OpenCV 中应用公式并传输图像
- 在不传输的情况下更改 Win32 中的串行端口波特率
- Vulkan 的传输队列系列功能和显卡支持:条件检查是否准确?
- 如何使用CAPL的诊断功能获取CAN传输的数据(256字节)?
- 如何通过ROS将realsense数据传输到其他设备
- 将音频从浏览器流式传输到WebRTC本机C++应用程序
- 将FFMpeg AVFrame对象从C++应用程序流式传输到Python的最佳方法?
- 使用IMFSourceReader(Microsoft媒体基金会)进行音频流传输
- 在PROGMEM中添加更多数据会中断Arduino Mega 2560上的SPI传输
- QTcpSocket 在 RemoteHostClosedError 后重新连接到服务器时无法传输数据