How to erase cin info?

My program is set up to ask the user for one letter(prompt1), and then a string of letters(prompt2). I have the logic correct but there's a small problem with the program. Whenever the user enters multiple letters at the first prompt, the rest of the letters are stored and used for the second prompt's input. How can I clear my cin and make sure I get input from the user a second time?

This is what I have right now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int  main(){
char oneLetter;
string multipleLetters;

cout << "Enter one letter: " << endl;  // if user enters multiple letters here, the program                
                                                            // doesn't even ask user for second input, it just
                                                            // uses the rest of the letters as second input
cin >> oneLetter;

//do stuff with one letter

cout << "Enter a string of letters: " << endl;
cin >> multipleLetters;

// do stuff with multiple letters
}
Last edited on
Try cin.sync() after cin >> oneLetter.
The sync() method won't do what you want. What you need to remember is that the user will always press ENTER after every input. So you need to use cin.ignore( numeric_limits <streamsize> ::max(), '\n' ); to get rid of anything left in the input buffer -- at least to synchronize to the EOL in readiness for the next input.

Hope this helps.
@Duoas.

Hey, just curious as to why you would say it doesn't work. I compiled this:

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

int  main()
{
	char oneLetter;
	string multipleLetters;

	cout << "Enter one letter:\n";
	cin >> oneLetter;
	cin.sync(); //clear the buffer

	cout << "\nEnter a string of letters:\n";
	cin >> multipleLetters;

	cout << "\nOutput: " << oneLetter << "     " << multipleLetters;
	cin.sync(); //clear buffer for get()
	cin.get(); //pause
}

... and entered 123456 (enter) then 789 and got the following output:

Output: 1     789
.
Last edited on
Cuddlebuddie928 wrote:
entered 123456 (enter) then 789 and got the following output:
Output: 1 789

Your compiler must be treating "cin.sync()" as if a call to cin.ignore. Other compilers don't: the same program with GCC on linux prints Output: 1 23456
Topic archived. No new replies allowed.