Search code examples
c++iostreamcingetlinec++98

eofbit not set with clear in C++98


I have to make a program for homework that reads some user inputs using std::cin and std::getline(), but it is specified that the program should exit only when EXIT is typed.

I am currently trying to get Ctrl-D to do nothing, and multiple people have told me to use this snippet:

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;
}

The problem is, this does nothing when I test it. The eofbit flag is not reset, and getline() just continuously fails after that.

Here is my code:

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);
}

I have to code in C++98. I compiled with clang++ using the following flags: -Wall -Werror -Wextra -std=c++98

Does anyone have an idea of what could be causing this to fail?

I have tried editing what was inside the ignore() call, tried swapping the order between clear() and ignore(), verified the eofbit variable which is still set after a call to clear().


Solution

  • This should work. You havent reset stdio stream from C which is giving you a new EOF. Remove the sync and you should be good.

    #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 << "Invalid command, commands are ADD, SEARCH and EXIT" << std::endl;
        }
        return (0);
    }