Click to See Complete Forum and Search --> : clear the istream-buffer
Suzi
September 25th, 2002, 04:15 AM
If I want to read to a buffer a specified number of characters I'll use:
char text[12];
...
cin >> setw(sizeof(text) / sizeof(char)) >> text;
But if the user writes more than 11 characters I'm in trouble when I want to read next time:
int i = 0;
...
cin >> i;
I'm gessing that the characters the user put in that the first cin ignored still is in the istream-buffer, but I don't know how to clear the istream-buffer.
I tryed to use also:
cin.getline(text, 12);
but it works only worse.
Any suggestions?
Suzi
Philip Nicoletti
September 25th, 2002, 06:41 AM
maybe something like this ??
cin >> setw(sizeof(text) / sizeof(char)) >> text;
cin.ignore(80,'\n'); // ignore rest of line
Suzi
September 25th, 2002, 07:36 AM
Yes, it works, thanks.
But if the user writes more than 80+12 characters it's still the same problem, right?
This should work I think, but is there a better way?
cin >> setw(sizeof(text) / sizeof(char)) >> text;
cin.ignore(80,'\n');
while(cin.gcount() == 80)
cin.ignore(80,'\n');
/Suzi
Philip Nicoletti
September 25th, 2002, 07:57 AM
The way Josuttis does it in his book is to put
the maximum value for int as the first parameter
of the ignore() function :
#include <limits>
//
//
//
cin.ignore(numeric_limits<int>::max(),'\n');
AnthonyMai
September 25th, 2002, 08:30 AM
The ignore() member function is intrinsically frauded and should never be used.
What do you end up ignoring, when you call ignore()? The stuff you ignored must be either valid data or invalid data, right?
If you ignored VALID data, you are doing a bad thing, you are throwing away legitimate data that you should read in.
If you ignored INVALID data, you are doing a bad thing, too. The input contains invalid data that shouldn't be there at first place, so this is an error condition that you should deal with properly, instead of just ignoring them.
Like the "123a" case the other poster raised. the "a" doesn't belong there, it is invalid data. You can't just ignore it, you should report it as an error.
The only correct use of ignore() is when it ignored nothing. But then you are wasting your time doing nothing useful. So it is still a bad usage of ignore().
If you have to use ignore(), something is fundamentally wrong.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.