beginnerjohn
beginnerjohn

Reputation: 43

C++ string.empty not working

I'm trying to use .empty() so pressing enter in the following code will not execute the if statement and the do-while loop will break. When I try this code, hitting enter does nothing: it just continues indenting until I enter more data. I looked up .empty() and I think I am using it correctly. Why isn't this code working?

void Student::read()
{
string g = " ";

cout << "Enter the students name: ";
getline(cin, new_name);
cout << endl;

do
{
    cout << "Please enter a letter grade <E to quit>: ";
    cin >> g;

    if(!g.empty())
    {
        addGrade(g);
    }
}while(!g.empty());
}

Upvotes: 0

Views: 1190

Answers (2)

Steephen
Steephen

Reputation: 15824

std:;string:empty() is working as expected in this. As Benjamin pointed out instead if you use getline(cin, g); in place of cin>>g you can achieve what you are expected:

int main()
{
string g = " ";
std::string new_name;
cout << "Enter the students name: ";
getline(cin, new_name);
cout << endl;

do
{
    cout << "Please enter a letter grade <E to quit>: ";
    getline(cin, g);

    if(!g.empty())
    {
        std::cout<<"here";
        //addGrade(g);
    }
}while(!g.empty());

return 0;
}

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

The problem is nothing to do with string.empty(), it is this line:

cin >> g;

That operation is whitespace delimited. That is to say, it skips all leading whitespace, and then once it has started consuming non-whitespace characters, it stops on the next whitespace if finds. So you can just press enter all day long, and it will be ignored, because pressing enter causes a newline character ('\n'), which is whitespace.

If you want line oriented input, use getline instead of operator>>.

getline(cin, g);

Upvotes: 4

Related Questions