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?