getline command

The second getline in my code doesn't seem to be working. The first get line reads the input fine but the second getline for the variable "occupation" doesn't seem to be getting called at all. It outputs "Occupation" and then straight to "Number of children" without asking for the input to "Occupation". It will allow me to input my occupation if I use cin instead of the second getline. Any idea why the second getline isn't being called?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;   

int main()
{
	string name, occupation;
	int numberOfChildren;
	double taxableIncome, tax;

	cout << "Name: ";
	getline(cin, name);
	cout << "Taxable income: ";
	cin >> taxableIncome;
	cout << "Occupation: ";
	getline(cin, occupation);
	cout << "Number of children: ";
	cin >> numberOfChildren;


Last edited on
Put
cin.ignore(); before getline(cin, occupation);

It clears the buffer I believe. Not sure of the exact technicalities.
You are mixing formatted (<<) and unformatted (getline) input. Don't do that.

Rule of thumb: always use getline() to read user input, then use a stringstream to extract information.

This is because the user will always press ENTER at the end of every input.

This forum is replete with information about this topic. Good luck!
Topic archived. No new replies allowed.