我试图获得用户输入,直到ctrl-d被击中.如果我是正确的,控制d会发出一个EOF信号,所以我试过检查cin.eof()是否为真但没有成功.
这是我的代码
string input;
cout << "Which word starting which year? ";
while (getline(cin, input) && !cin.eof()) {
cout << endl;
...
cout << "Which word starting which year? ";
}
Run Code Online (Sandbox Code Playgroud)
因此,您希望阅读直至EOF,只需使用while循环和getline即可轻松实现:
std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这里使用getline(getline返回流)你得到输入,如果你按Ctrl+D,你就会打破while循环.
值得注意的是,在Windows和onLinux上触发的EOF不同.您可以从命令行使用CTRL+D(for*nix)或CTRL+Z(对于Windows)模拟EOF .