What is cin.sync()?

I was wondering if anyone could give me a definition/explanation on what cin.sync() is.
Consider this:
1
2
3
4
5
6
7
8
9
10
cout << "Enter Text: ";
std::string str;
cin >> str;
cout << "Enter Number: ";
int n;
cin >> n;
cout << "Enter Another Number: ";
int n2;
cin >> n2;
cout << "You Entered: " << str << ", " << n << ", " << n2 << endl;


There are two problems with this code. Let's look at the first problem - what happens when we type in two words?
Enter Text: Hello, World!
Enter Number: 
Enter Another Number: 
You Entered: Hello,, 
and the rest of the output would be undefined. This is because it only reads in stuff until a space, so the leftover text is there for when it tries cin >> n, which won't work. To fix it, we can add cin.sync() after the cin >> str, which will synchronize the input stream with whatever has been entered.

The second problem is that this program would end before we saw the output - this can be fixed with cin.get() or cin.ignore(), but if the user typed in two things for Another Number, it would get that and end. To solve this, you can add cin.sync(); cin.ignore();, which will hold the window open until you press enter.
@L B
perfect example, thanx.
i used to use cin.get() but got hit by some strange behavior (i know it s dumb).
will it work the same after a getline(cin,stringname) ?
Last edited on
cin.sync() basically ignores anything that could be left in the stream - it should work fine.
Topic archived. No new replies allowed.