user1595932
user1595932

Reputation: 135

C++ what is wrong with this do while loop

I am trying to input a string. It's working fine when I input something like John.

But if I input something like John Smite I end up in an endless loop and a terminal crash.

string fullname;

do{
    cout << "Please input the Full Name of the user: ";
    cin >> fullname;
}while(fullname=="");

Upvotes: 0

Views: 308

Answers (3)

jrok
jrok

Reputation: 55395

As to why you get an infinite loop - operator>> overload for std::string will first discard any leading whitespace and then read up to either next whitespace or the end of avaliable input.

When you enter "John Smite", first iteration reads "John", second iteration reads "Smite" and then there's no more input for subsequent iterations. The problem is that your implementation seems to clear fullname before it attempts a read. But because the stream is not in good state anymore, no more reads are possible and there's your infinite loop.

You could do something like this instead:

string temp;
string fullname;
do {
    cin.clear(); // clear any error flags
    do {
        if (cin >> temp) fullname += temp + ' ';
    } while (cin.good());
} while (fullname.empty());

This has a (good) side effect that it collapses multiple adjacent whitespace characters, but it's still pretty clunky.

Much better way would be to just say

do std::getline(std::cin, fullname); while (fullname.empty());

Upvotes: 0

Mihriban Minaz
Mihriban Minaz

Reputation: 3039

You can try this one:

do{
cout << "Please input the Full Name of the user: ";
cin >> fullname;
}
while(fullname.length() == 0);

Upvotes: 1

mjgpy3
mjgpy3

Reputation: 8937

The space is throwing cin off. You should use getline.

Upvotes: 1

Related Questions