Rock Lee
Rock Lee

Reputation: 9566

Getline() combined with cin.ignore() is not storing variable? (Bug)

I don't think this question is not a duplicate of this. Even though it is caused by the same thing, it is a different manifestation of the problem.


The terminal output when I run this program looks like this (my input is 1 and Rock Lee followed by enter):

Enter a number: 1

Enter your name: Rock Lee

Name is blank.

However, the name shouldn't be blank. Why is the name variable ""? How do I fix this bug? Here is the code:

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main () {
    
    int num;
 
    string name;
    
    cout << "Enter a number: ";
    cin >> num;
    
    cout << "Enter your name: ";
    getline(cin, name, '\n');
    
    cin.ignore (1000, '\n');
    
    if (name == "")
    {
        cout << "Name is blank.";
        return -1;
    }
    
    return 0;
}

Also, please note that I want to use Getline() in the solution, and I want to be able to read an entire line (so the name can be anything, not just first and last name).

When I tried commenting out cin.ignore(1000, '\n');, it gave this output which is also incorrect:

Enter a number: 1

Enter your name: Name is blank.

It doesn't even give me a chance to type in my name. How do I fix this?

Upvotes: 0

Views: 422

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30569

cin >> num reads until it sees whitespace, but it doesn't discard the whitespace, so it leaves '\n' in the input. Your call to getline sees it and immediately returns, filling name with an empty string. You need to call cin.ignore before getline to ignore the '\n' that cin::operator>> left laying around.

Upvotes: 2

Related Questions