c++ - 如何使用 program.exe < text.txt 使用 C++ 读取输入

标签 c++ file iostream cin

我必须根据这些规则读取输入:

"The input consists of several lines of text. Some lines may be empty. The input can be fed from a file, using a line such as prog.exe < input.txt in which case the end of input is indicated appropriatelly by the operating system. If you enter input using a keyboard, there is normally a way to signal the end of input with some control key, depending on the operating system (e.g., Ctrl+d in Unix/Linux-style systems, and Ctrl+z in Microsoft systems)."

以前我一直是这样做的

while(getline(cin, data)) {
     if(data == "0") break;
     / * do stuff */
}

因此,我可以读取任意多行并进行预计算,然后在完成后键入 0 并结束我的程序。我尝试在 .txt 文件中每行输入一个列表,然后调用 program.exe < myfile.txt但什么也没发生。

这是什么< file.txt正在做?

在这样调用我的程序时,如何正确处理其中的内容?

当您按下 ctrl+z 时,我如何让它计算东西?

最佳答案

解释你的练习文本:

使用 command1 < file1执行 command1 , 与 file1作为输入源(与键盘相对)。

这称为重定向标准输入。

std::cin将从 file1 获得输入而不是从键盘。

输入文件的结尾类似于CTRL+Z(在微软系统上,CTRL+D 在大多数其他人身上)。曾经 std::getline() 到达文件末尾(或者你读到一行只有“0”),你将退出你的 while -loop 然后你可以对 data 进行计算你已经收集了(并且可能存储在某个容器中)。

关于c++ - 如何使用 program.exe < text.txt 使用 C++ 读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359695/

相关文章:

c++ - 在一个声明语句中定义一个函数和一个变量

c++ - 成员函数指针的解决方法是一个糟糕的黑客?

c++ - getline() 可以用于从 fstream 获取 char 数组吗

c - 通过C操作文件制作排行榜前5名

c++ - 虽然不是新线

c++ - ostringstream 插入器是否使用当前语言环境?

c++ - operator+ 的规范实现涉及额外的移动构造函数

c++ - 为什么指针可以为NULL

java - 如何使用 MBean 上传文件?