Logic error using the getline() function

Hello,

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
     #include <iostream>
     
     using namespace 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.
A quick fix to this is to declare a char variable, call it myChar or something along those lines. Before the line prompting for the job, add in:

cin.get(myChar)

The problem is that whitespace is a delimiter in strings.
Last edited on
Don't mix formatted and unformatted input. Use getline() everywhere, then convert the input to whatever data type you need using an std::stringstream.
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)
Thanks everyone.
cin.ignore(); Just worked fine.
Tricky thing to mix those cin and getline functions.
Topic archived. No new replies allowed.