【发布时间】:2015-10-16 02:55:19
【问题描述】:
所以我正在尝试
a) 允许用户输入一个字符串,直到他们键入 exit
或
b) 将文件从标准输入(a.out < test.txt) 重定向到文件末尾,然后终止
我对代码的尝试:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
string input = "";
while(true){
cout << "Enter string: ";
while(getline(cin, input)){
if(input == "exit" || cin.eof()) goto end;
cout << input << "\n";
cout << "Enter string: ";
}
}
end:
return 0;
}
这会导致重定向问题,当我使用命令 a.out < test.txt 时,我得到一个无限循环(其中 test.txt 包含一行“hello”)
用户输入似乎工作正常
我使用 getline 是因为在实际程序中,我需要逐行读取文件,然后在移动到文件的下一行之前操作该行
编辑:我的问题是,如何终止考虑用户输入和重定向的循环?
【问题讨论】:
-
你的代码对我有用ideone.com/pj0xID
标签: c++ file stdin cin io-redirection