Clearing input buffer


C

Carol Pedder

Hello all, may I ask a question?

Having just started C++ (using microsoft visual studio), I am using cin/cout
for console applicarions (yes I know it doesn't happen in the real world!)
and I'm finding it difficult to track down a method of clearing the input
buffer after a cin (to get rid of potential rubbish).

cin.flush() has been mentioned, but isn't an option on visual studio and
cin.ignore() requires you to specify number of chars to ignore.

Any help much appreciated.

Regards

Carol
 
Ad

Advertisements

I

Ioannis Vranos

Carol said:
Hello all, may I ask a question?

Having just started C++ (using microsoft visual studio), I am using cin/cout
for console applicarions (yes I know it doesn't happen in the real world!)
and I'm finding it difficult to track down a method of clearing the input
buffer after a cin (to get rid of potential rubbish).

cin.flush() has been mentioned, but isn't an option on visual studio and
cin.ignore() requires you to specify number of chars to ignore.


cin.ignore() with '\n' as the terminal character, assuming you want to
remoove the '\n' that remains in the stream.

E.g. cin.ignore(1000, '\n');
 
C

Chris \( Val \)

| Hello all, may I ask a question?

Sure.

| Having just started C++ (using microsoft visual studio), I am using cin/cout
| for console applicarions

Well, I don't know what an 'applicarion' is, but let's
see if we can work it out <g>.

| (yes I know it doesn't happen in the real world!) and

What do you mean by that ?

| I'm finding it difficult to track down a method of
| clearing the input buffer after a cin (to get rid of
| potential rubbish).

std::cin.clear();

....will reset the stream state back to a good state.

You can then follow that call with:

std::cin.ignore( std::numeric_limits<
std::streamsize>::max(), '\n' );

....to remove all remaining junk from the stream.

It should now be ready for another read operation.

| cin.flush() has been mentioned, but isn't an option on visual studio and

It's not an option, because the C++ standard does not define
such an operation for an input stream.

| cin.ignore() requires you to specify number of chars to ignore.

Not always - You can use the default call:
cin.ignore();

....which will ignore '1' character from the stream,
if one exists.

[snip]

Cheers.
Chris Val
 
R

Ron Natalie

Carol said:
cin.flush() has been mentioned, but isn't an option on visual studio and
cin.ignore() requires you to specify number of chars to ignore.
flush() does not affect the input side of streams. If it's been mentioned
they mentioners were wrong.

cin.ignore works, it takes both a count and a delimeter.

In actuality, what you think you're asking for is probably impossible.
There's no concept of a "non-blocking" input in standard C++, that is,
there's no way to tell that there isn't pending unread input.

So in a trully portable program, you can't rely on that methodology.
The best you can hope for is to read up to the next newline or other
sentinal character when you want to discard input.
 
C

Carol Pedder

Ron said:
In actuality, what you think you're asking for is probably impossible.
There's no concept of a "non-blocking" input in standard C++, that is,
there's no way to tell that there isn't pending unread input.

So in a trully portable program, you can't rely on that methodology.
The best you can hope for is to read up to the next newline or other
sentinal character when you want to discard input.

Thanks for all your replies. I think I am asking the impossible.

What I really wanted to do was clear the input buffer in the event of trying
to input a letter to an integer variable, which sends the program into a
loop as it attempts to extract an integer from the buffer ad infinitum.

I realise that it is much better practice to use getch() and validate input
properly, but could not understand why the output buffer can be flushed, but
not the input buffer - I still can't, but I guess that's just the way it
works!

Thanks again

Carol
 
I

Ioannis Vranos

Carol said:
Thanks for all your replies. I think I am asking the impossible.

What I really wanted to do was clear the input buffer in the event of trying
to input a letter to an integer variable, which sends the program into a
loop as it attempts to extract an integer from the buffer ad infinitum.

I realise that it is much better practice to use getch() and validate input
properly, but could not understand why the output buffer can be flushed, but
not the input buffer - I still can't, but I guess that's just the way it
works!


Check this sample code from TC++PL 3, page 620:



void read_a_line(int max)
{
// ...
if (cin.fail()) { // Oops: bad input format
cin.clear() ; // clear the input flags (21.3.3)
cin.ignore(max,´;´) ; // skip to semicolon

if (!cin) {
// oops: we reached the end of the stream
}
else if (cin.gcount()==max) {
// oops: read max characters
}
else {
// found and discarded the semicolon
}
}
}



So if you want to guard against invalid input and remove the remaining
'\n' and other trash from the stream, one approach you can follow is this:



while(cin)
// ...


if(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n')
}


//If you want to detect the end of file
if(cin.eof())
// ...
 
Ad

Advertisements

C

Carol Pedder

Ioannis said:
So if you want to guard against invalid input and remove the remaining
'\n' and other trash from the stream, one approach you can follow is this:

.....
if(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n')
}

Placing this code after my cin does the trick - a perfect solution, thanks a
lot.

Regards

Carol
 
Joined
Sep 24, 2006
Messages
4
Reaction score
0
cin.clear() and cin.ignore(10, '\n')

I am also a beginner C++ programmer.

Use this:

x = however many characters you wish to ignore (usually a large number);
cin.clear;
cin.ignore(x, '\n');

In the snippet below, I want the user to enter his/her choice as an integer but he/she could possibly enter a decimal such as 1.2 or 2.9.
void printmenu(){
int Choice;
string buffer;
cout<<"Please choose what you would like to do." <<endl;
cout<<"1. Add"<<endl;
cout<<"2. Subtract"<<endl;
cout<<"3. Exit" <<endl;
cin>>Choice;
cin.clear();
cin.ignore(10, '\n');
}

If the user enters a decimal number, then Choice will become the integer value but cin will still keep the 0.x part and use it later.

By adding the following:
cin.clear();
cin.ignore(10, '\n');
I throw away any "rubbish" input.

What do you think?
 
Last edited:
Joined
Dec 2, 2008
Messages
9
Reaction score
0
I Found it! ... I think.

Hi guys,
I've been having difficulties with this for a while now too, and I just happened to stumble upon some info about istream::sync
Apparently I can't post links (it says I haven't posted enough to) so here's the url to where I found out about it: cplusplus.com/reference/iostream/istream/sync/

and here's a little code snippet of how it might be used.
Note: This code worked as is for me.
Code:
#include <iostream>
using namespace std;

int main()
{
[INDENT]char firstThing;
char secondThing;
cout << "type something\n>";
cin >> firstThing;
cin.sync();
cout << "\ntype something else\n>";
cin >> secondThing;
cout << "\nthe first thing you typed started with a(n): " << firstThing <<endl;
cout << "the second thing you typed started with a(n): " << secondThing <<endl;
system("PAUSE");
return 0;[/INDENT]
}
which I Believe is for exactly what we've all been looking for, ignoring everything in the input buffer so we can ask the user for input and not have the extra garbage on the end of something previous show up on it's own.

I don't know for sure that this is what we want, but it looks like it, and it's working on everything I've made so far (haven't tested any of it outside of windows yet though).

Here's hoping:veryprou:.
 
Last edited:
Ad

Advertisements

Joined
Dec 30, 2010
Messages
1
Reaction score
0
Clear input queue

Here's another solution for anyone who's still interested.

PHP:
cin.clear();
while (cin.get() != '\n')
  continue;

It loops through each character in the input queue until it finds the newline character.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top