Trouble clearing cin or getline() buffer - !!!

I have the code below, searching an array for user entered 'city'. Then search and when found, return the city, tax rate, and county.
I want to ask the user if they want another search; but when I use 'cin >> answer' for 'Y' or 'N'. The buffer still contains the previous values.

I have tried cin.clear(), cin.ignore(), before each input entry. Nothing is working. Thoughts?


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
...
...
answer = 'Y';

do{

cout << "What city are you looking for?    ";

	getline(cin, input);

	while (index < SIZE && !found)
	{	
	        if (Cities[position].city == input)
		{
			found = true;
			position = index;			
		}
		index++;		
	}		

	if (position == -1)
	{
		cout << "Not found\n";				
	}
	else 
	{
		cout << PRINT INFORMATION...
	}
cout << "Do you want another search?    ";
cin.clear();
cin.ignore();
cin >> answer;

}while(answer == 'Y' || answer == 'y')
Last edited on
In this case you should be checking the status of cin, and only clear() and ignore() if there is an error in the stream state. The getline() function should not leave anything behind, it extracts the end of line character and discards it, so you should not need the ignore() at all in this case.

If you were to use the extraction operator>> is when you usually have problems with the new line character being left in the input buffer, but getline(), without the optional third parameter, doesn't have this problem.

I think getline() should not need cin.clear() after it. However, cin >> answer might, as "\n" might still be in the stream from when you press enter. I had an issue with this when I was using a getline after a cin and needed to clear the stream for it to work.
Topic archived. No new replies allowed.