eofbit 在 C++ 中未使用clear设置

问题描述 投票:0回答:1

我必须编写一个作业程序,使用

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 << "Ivalid 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()

后仍然设置
c++ iostream cin getline c++98
1个回答
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)。该行为可能会因操作系统和终端设置而异。

© www.soinside.com 2019 - 2024. All rights reserved.