How to use getline(cin)

Please help. This is my code, eventually when I run the code the part on "Enter Name" will be skipped. Please tell me what went wrong. Thank you.

example input of name: Alvin Keith

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	int id;
	std::string n;
	double s;
	
cout << "Enter tax ID ";
cin >> id;
cout << "Enter name ";
std::getline (std::cin,n);
cout << "Enter salary ";
cin >> s;

cout << id << " " << n << " " << s << endl;
}
Last edited on
I don't know the explanation of this problem, but i know how to fix it.

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
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <string>
using std::string;
using std::getline;

int main(){

int id;
string name;
double salary;

cout<<"Enter tax ID: ";
cin>>id;
cin.ignore();
cout<<"\nEnter name: ";
getline(cin,name);
cout<<"\nEnter salary: ";
cin>>salary;

cout<<"\n\n"<<id<<' '<<name<<' '<<salary<<endl;

return 0; //indicates success
}//end main 



Enter tax ID: 123

Enter name: Eyenrique

Enter salary: 321


123 Eyenrique 321

Wow! It worked. I tried adding in cin.ignore() and it worked.
Why is that so?
Here, cin>>id; the user types in the value for id and presses the enter key. The cin >> operator will first ignore any leading whitespace, then read the value of the id which is an integer. The input operation stops as soon as it reaches the end of the integer, and leaves the newline character '\n' sitting in the input buffer.

Next, the getline() operation will read everything up to the newline, which is read and discarded. The result is an empty string is read by getline.

In order to avoid this, you need to remove the newline from the input buffer. That's what the cin.ignore() does. Though as written, it ignores just one character. If the user had entered any spaces after typing the id, this would not be sufficient as there is more than one character to be ignored. You could use cin.ignore(1000, '\n') to ignore up to 1000 characters, or until the newline is reached.
Thanks @Chervil!
Wow! Thank you so much Chervil & eyenrique! :)
Topic archived. No new replies allowed.