Hi!

I read the clearing input buffer article on the top of the c++ forum but I don't really get it, and it doesn't work.

This is my problem, I know that cin is just like a file in that it has a buffer (correct me if I'm wrong, I think I'm right) and can use the same things that istream objects can use.

so, that (if I'm right) would mean that this is legal cin.ignore . but for some reason it's not... what's wrong? the error occurs in just the one spot and it seems to not be related to any I did in the program elsewhere.

just ask if you want to see the source

thanks,
Jt

Remember cin.ignore has two parameters.

cin.ignore(1000, '\n');

This is to clear the input stream useful with while mixing cin.get(param1) and cin >> variable1.

Example 1

/*
	Purpose: threads/354626
	Name: Saith
	Date: 3/20/11
	*/

#include<iostream>
using namespace std;


int main(){

	int var1;
	char var2;

	cout << "Input some number.\n";
	cin >> var1;
	cout  << "Your number is "<< var1 << endl;

	cout << "Input another number.\n";
	cin.get(var2);
	cout  << "Your number is "<< var2 << endl;

	return 0;
}

Input:
1
// c // would have been the second input

Output:
1
[blank space]


and will not bother pausing for a keystroke due to a character already in cin (the '\n' character). If you add the cin.ignore(para1, para2); syntax, the '\n' character will be removed from the stream input along with any other value.

Example 2

/*
	Purpose: threads/354626
	Name: Saith
	Date: 3/20/11
	*/

#include<iostream>
using namespace std;


int main(){

	int var1;
	char var2;

	cout << "Input some number.\n";
	cin >> var1;
	cin.ignore(1000, '\n');
	cout  << "Your number is "<< var1 << endl;

	cout << "Input another number.\n";
	cin.get(var2);
	cout  << "Your number is "<< var2 << endl;

	return 0;
}

Input:
1
c
Output:
1
c

Edited 5 Years Ago by Saith: n/a

Comments
Nice :)

Thank you, this has been plaguing me for a long time and it's very annoying. However, this helped me a lot and now it works almost every time.

Thanks again,
jt

This question has already been answered. Start a new discussion instead.