所以我正在尝试要么
a) 允许用户输入一个字符串,直到他们输入退出
或
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 是因为在实际程序中我需要逐行读取文件,然后在移动到文件的下一行之前操作该行
编辑:我的问题是,如何终止考虑用户输入和重定向的循环?
最佳答案
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
string input = "";
while(cin && cout<<"Enter string: " && getline(cin, input)){
//check both cout and cin are OK with the side effect of
// writing "Enter string" and reading a line
if(input == "exit") return 0; //no need for a goto
cout << input << "\n";
}
if(cin.eof()) return 0; //ended because of EOF
return 1; //otherwise, the loop must have broken because of an error
}
保持简单。您不需要外循环和 cin.eof()
在 while block 内永远不会为真,因为 if cin.eof()
为真,则 getline
返回 cin
的表达式转换为 bool 将转换为 false,从而结束循环。
如果 cin
则循环结束遇到 EOF 或错误。
关于c++ - 如何期望来自重定向和用户输入的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161812/