Keep looping until user enters a blank line?

So I've run into the following problem. My goal is to create a loop that keeps taking user input over and over until the user doesn't enter anything into 'cin >>', leaves the line blank, and simply presses the ENTER key to move on, at which point the program is supposed to break out of the loop and continue on with the rest of program execution. Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
do { 
        cout << "\nEnter a name: ";
        cin >> input1;
        if (input1.empty())
        {
            break;
        }
        else
        {
            user_name = input1;
        }
       } while (!input1.empty());


As you can see, I've already tried using the empty() function, but that didn't work, the program simply stays in the loop and doesn't break out, no matter how many times I press enter. It just keeps prompting me to enter a name. I've also tried using something like

if (input1 == "")

but that doesnt work either. Can anyone help? How do I break out of this loop?
You need to use the getline() function that takes data from the std input stream and directs it to the std::string:

1
2
3
4
5
6
7
8
9
10
11
while(true)
{
    cout << "\nEnter a name: ";
    string input;
    getline(cin, input);
        
    if (!input.empty())
        user_name = input;
    else
        break;
}
Last edited on
Topic archived. No new replies allowed.