flush cin

May 16, 2009 at 9:28pm
Hi
How can i flush cin so that i can read a string with spaces after reading an int?
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;
int main(){
	int n;
	string x;
	cout << "n? ";
	cin >> n;
	cout << "x? ";
	getline(cin, x);
}


Other solutions apreciated.

Thanks
May 16, 2009 at 9:33pm
Using std::cin>>std::flush; or std::cin.flush() will flush I believe.
May 16, 2009 at 10:16pm
I must be doing something wrong ... can't flush it like that.

The only way i managed this to work was:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;
void myFlush(){
	int ch;
	while ((ch = cin.get()) != '\n' && ch != EOF);
}
int main(){
	int n;
	string x;
	cout << "n? ";
	cin >> n;
	myFlush();
	cout << "x? ";
	getline(cin, x);
}


But that's just a little too mush for something so simple as reading a string.
How do you read string for simple program examples?!
May 16, 2009 at 11:24pm
You can call cin.sync() or cin.ignore()
May 17, 2009 at 10:46am
That's more like it.
Thanks
Topic archived. No new replies allowed.