Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading