how to use cin.ignore

if the user types in a letter for id2 , the first getline will fall through (it will be empty),

i thought i would have taken care of that by using

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

cin.clear();



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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

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

int main() {

	int id , id2;
	string name , name2;
	double salary;

	cout << "Enter tax ID: ";
	cin >> id;

	cout << "Enter tax ID2: ";
	cin >> id2;


	//cin.ignore();


	cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	cin.clear();

	cout << "\nEnter name: ";
	getline(cin, name);



	cout << "\nEnter name2: ";
	getline(cin, name2);


	cout << "\nEnter salary: ";
	cin >> salary;

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


	system("pause"); 

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

/*


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.


*/
Last edited on
You need to clear the error flags before using ignore.

1
2
3
cin.clear();

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
yes , i tried this and it work ... what is the reasoning behind this ?
All read operations (including ignore) will fail automatically if an error flag is set. That's why you need to clear the error flags before you use ignore, otherwise it will do nothing.
Last edited on
Topic archived. No new replies allowed.