I have written a small sample program that reflects the problem that I'm having in my larger program.
When I use the getline() function for the first time in this code snippet to receive the input string from the user, the user does not have the chance to answer the question and the program just asks the next question.
Everything works fine but I can't explain what happens with this logic error.
#include <iostream>
usingnamespace std;
int main() {
float salary;
cout << "How much money would you like to earn every year?" << endl;
cin >> salary;
string job;
cout << "What is your job?" << endl;
cin >> job;
// Why can't the user answer this question?
string name;
cout << "What's your name?" << endl;
getline(cin, name);
string country;
cout << "What country are you from?" << endl;
getline(cin, country);
string location;
cout << "Where do you live?" << endl;
getline(cin, location);
return 0;
}
And this is the output of this code:
How much money would you like to earn every year?
50000
What is your job?
Dental Lab Assistant
What's your name?
What country are you from?
USA
Where do you live?
New York
I hope someone explains to me what's going on.
Thanks for the help.
Its best to use cin.ignore(); after you use a cin command to clear the buffer as it remebers the enter that you pushed. (getline is usually the one that misbehaves! Hence why you can't answer the question as it has assumed the answer is enter from the previous cin)