我必须编写一个作业程序,使用
std::cin
和 std::getline()
读取一些用户输入,但指定该程序仅在键入 EXIT
时退出。
我目前正在尝试让 Ctrl-D 不执行任何操作,并且很多人告诉我使用此代码片段:
if (std::cin.eof()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //some have told me to put nothing there, has not changed the behavior.
continue;
}
问题是,当我测试它时,这没有任何作用。
eofbit
标志不会重置,并且 getline()
之后会不断失败。
这是我的代码:
int main()
{
PhoneBook phone;
std::string input;
while (true){
std::getline(std::cin, input);
if (std::cin.eof()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if (input == "ADD")
phone.addContact();
else if (input == "SEARCH")
phone.search();
else if (input == "EXIT")
break;
else
std::cerr << "Invalid command, commands are ADD, SEARCH and EXIT" << std::endl;
}
return (0);
}
我必须用 C++98 编写代码。我使用以下标志使用
clang++
进行编译:-Wall -Werror -Wextra -std=c++98
有人知道什么可能导致此失败吗?
我尝试编辑
ignore()
调用中的内容,尝试在 clear()
和 ignore()
之间交换顺序,验证在调用 eofbit
后仍然设置的 clear()
变量。
这应该有效。您尚未从
stdio
重置 C
流,这将为您提供新的 EOF
。删除同步,你应该就好了。
#include <iostream>
#include <limits>
int main()
{
std::ios_base::sync_with_stdio(false);
std::string input;
while (true){
std::cin >> input;
if (std::cin.eof()) {
std::cout << "Ignore" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if (input == "ADD")
std::cout << "Adding"<< std::endl;
else if (input == "SEARCH")
std::cout << "Adding"<< std::endl;
else if (input == "EXIT")
break;
else
std::cerr << "Ivalid command, commands are ADD, SEARCH and EXIT" << std::endl;
}
return (0);
}
根据您给出的特定要求以及使用
C++98
与 clang++
的约束,处理文件结束条件可能有点棘手。 std::cin.eof()
的行为并不总是简单,因为按下 Ctrl-D 后可能不会立即设置。
要解决此问题,您可以修改循环条件以检查
std::cin.eof()
和 std::cin.fail()
。当到达输入流末尾或遇到失败(可能在按 Ctrl-D 后发生)时,您可以跳出循环。
这是代码的更新版本:
#include <iostream>
#include <limits>
class PhoneBook {
public:
void addContact() {
// Implementation for adding a contact
std::cout << "Adding a contact...\n";
}
void search() {
// Implementation for searching
std::cout << "Searching...\n";
}
};
int main() {
PhoneBook phone;
std::string input;
while (!std::cin.eof() && !std::cin.fail()) {
std::getline(std::cin, input);
if (input == "ADD")
phone.addContact();
else if (input == "SEARCH")
phone.search();
else if (input == "EXIT")
break;
else
std::cerr << "Invalid command, commands are ADD, SEARCH, and EXIT" << std::endl;
}
return 0;
}
通过检查
std::cin.eof()
和 std::cin.fail()
,您可以涵盖输入流到达末尾 (Ctrl-D) 或由于其他原因遇到失败的情况。
注意: 此解决方案假设您的终端配置为在输入耗尽时生成 EOF 信号 (Ctrl-D)。该行为可能会因操作系统和终端设置而异。