"getline" trouble

After reading about how to use getline I thought I was using it correctly, but apparently I am not. When I run this program it does not give me the opportunity to input an employee name at all. What am I doing wrong?

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
30
31
32
33
34
35
36
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;

double FEDERAL = 0.15;
double STATE = 0.035;
double SS = 0.0575;
double MEDI = 0.0275;
double PENSION = 0.05;
double HEALTH = 75;

int main()
{
	double gross;
	double net;
	string name;

	cout << "Input gross amount earned:" << endl;
	cin >> gross;
	cout << "Input employee name:" << endl;
	getline (cin,name);

	net = (gross - (gross * FEDERAL) - (gross * STATE) - (gross * SS) - (gross * MEDI) - (gross * PENSION) - HEALTH);

	cout << name << endl;
	cout << fixed << setprecision(2) << "Gross Amount: ............ $" << gross << endl;
	cout << fixed << setprecision(2) << "Federal Tax: ............. $" << (gross * FEDERAL) << endl;
	cout << fixed << setprecision(2) << "State Tax: ............... $" << (gross * STATE) << endl;
	cout << fixed << setprecision(2) << "Social Security Tax: ..... $" << (gross * SS) << endl;
	cout << fixed << setprecision(2) << "Medicare/Medicaid Tax: ... $" << (gross * MEDI) << endl;
	cout << fixed << setprecision(2) << "Pension Plan: ............ $" << (gross * PENSION) << endl;
	cout << fixed << setprecision(2) << "Health Insurance: ........ $" << HEALTH << endl;
	cout << fixed << setprecision(2) << "Net Pay: ................. $" << net << endl;
}
put cin.ignore(); before getline
The reason is that using the std::cin with >> extracts all up to the first whitespace character, which it leaves in the stream. Successive calls will eat up the left over whitespace and discard it, but std::getline will end when whitespace is encountered. So, you should either do as @Yanson suggested and put std::cin.ignore() in front, which will eat up that newline character leftover from line 21.
Another thing to mention is that std::cin >> leaves a new line in the buffer and when you read with std::getline it reads until the newline. I would suggest using std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); to ignore anything that could possibly be left in the buffer. Say for example someone enters
10 asdf
if you don't ignore everything you will have junk read into getline.

[edit]or even if possible try not to mix and match them ( mainly with std::string's)[/edit]
Last edited on
Topic archived. No new replies allowed.