我必须根据这些规则读取输入:
"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/