c ++停止在ctrl-d上要求输入
c++ stop asking for input on ctrl-d
我正在尝试读取用户输入,直到按下 ctrl-d。如果我是正确的,ctrl+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? ";
}
所以你想读到 EOF,这很容易通过简单地使用 while 循环和 getline 来实现:
std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
这里使用 getline
(getline returns 输入流) 你得到输入,如果你按 Ctrl+D ,你跳出while循环
重要的是要注意 EOF 在 Windows 和 Linux 上的触发方式不同。您可以使用 CTRL+D (对于 *nix)或 CTRL+[=21= 模拟 EOF ]Z(对于 Windows)来自命令行。
请记住,您也可能会在其他情况下退出循环 - std::getline()
可能 return 某些失败的错误流,您可能也想考虑处理这些情况。
我正在尝试读取用户输入,直到按下 ctrl-d。如果我是正确的,ctrl+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? ";
}
所以你想读到 EOF,这很容易通过简单地使用 while 循环和 getline 来实现:
std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
这里使用 getline
(getline returns 输入流) 你得到输入,如果你按 Ctrl+D ,你跳出while循环
重要的是要注意 EOF 在 Windows 和 Linux 上的触发方式不同。您可以使用 CTRL+D (对于 *nix)或 CTRL+[=21= 模拟 EOF ]Z(对于 Windows)来自命令行。
请记住,您也可能会在其他情况下退出循环 - std::getline()
可能 return 某些失败的错误流,您可能也想考虑处理这些情况。