c++inputbuffercin

Does the empty() function in C++ work with cin?


I'm validating string input in C++, to make sure that the input is not empty. I know how to do it using the empty() function with getline(), but I want to know why it's not working when I use cin. When I use empty() with cin, I press enter to try and skip the input, but the empty() never returns true, so I never get re-prompted to enter the string. Is this because the '\n' left in the buffer from cin is counted? I would greatly appreciate the explanation for this.

string name;
cout << "Enter your name: ";
cin >> name;
while (name.empty()) 
{
    cerr << "Name can't be empty" << '\n';
    cout << "Enter your name: ";
    cin >> name;
}

Solution

  • By default, operator>> ignores leading whitespace (you can use std::noskipws) to disable that), and then it stops reading on trailing whitespace. In this case, whitespace includes the Enter key.

    So, the operator can never return an empty std::string value on success, only on failure (which your example is not checking for), as the std::string is erase()'ed before the operator attempts to read it:

    string name;
    cout << "Enter your name: ";
    if (cin >> name)
    {
        // success, name.empty() SHOULD always be false here...
    }
    else
    {
        // fail, name.empty() SHOULD always be true here...
    }