473,804 Members | 4,181 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Clearing input buffer

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
Jul 22 '05 #1
6 31079

"Carol Pedder" <ca***@pedder00 2.freeserve.co. uk> wrote in message
news:cl******** **@news5.svr.po l.co.uk...
| 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_li mits<
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
Jul 22 '05 #2
Carol Pedder wrote:
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');

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #3
Carol Pedder wrote:

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.
Jul 22 '05 #4

Ron Natalie wrote:

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
Jul 22 '05 #5
Carol Pedder wrote:
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())
// ...

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #6
Ioannis Vranos wrote:
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
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7500
by: Woodster | last post by:
I am using std::stringstream to format a string. How can I clear the stringstream variable I am using to "re use" the same variable? Eg: Using std::string std::string buffer; buffer = "value1" + " : " + "value2";
5
817
by: William Payne | last post by:
How do you get rid the contents in a std::stringstream? I'm using one in a for loop to format some status messages which I print to the screen. The stringstream member function clear() only clears flags (bits) in the stream, right? I solved it by declaring the stringstream inside the loop body even though I have need of another stringstream just after the loop. So for each iteration the constructor of the stringstream will be executed. Is...
4
7494
by: news.eircom.net | last post by:
Hello, How do you clear the contents of an ostringstream object? I've included some example code so you can see what I mean. t.i.a. Craig H. #include <iostream>
28
16641
by: Terry Andersen | last post by:
I have an array that I initialize to zero, like: Buffer = {0x00}; How do I in my code reset this array to all zeros ones more? Without running a whole for loop? Best Regards Terry
18
5707
by: JG | last post by:
Does anyone know a standard (or supported on Linux, Mac, Win32) way to clear a read stream buffer (standard ANSI C file stream)? I would even settle for a platform specific way of doing it. And no, I know I can use direct low level I/O or non-buffered to do reads, but for my app, I need the buffering. I can implement myself, but this is not optimal. Example, I open a read only file using fopen(). I periodically know
1
1953
by: kelharis | last post by:
Hello, I am writing a program that will run once, and once done, ask the user if they would like to use it again. It has to work with any answer beginning with "y". I am having trouble with clearing the buffer when I answer "yes" or anything other than "y" itself. It works perfectly when "y" is entered, now I just need to somehow accept the other yes words and clear the buffer once the "y" has been consumed. code is as follows: ...
11
13216
by: vbguy2008 | last post by:
Hi, I am coding a Windows Form Application in VB.NET 2008. I would like to clear the keyboard buffer or at least empty all outstanding key presses queued up for my application at certain points in my program. I looked at System.Console.Read, but that doesn't seems appropriate. I also looked into EnableWindow Lib "user32". I ran into a problem where I could disable the form, but was unable to enable the form. The code is:
12
2091
by: Tarique | last post by:
I have tried to restrict the no. of columns in a line oriented user input.Can anyone please point out potential flaws in this method? btw.. 1.I have not used dynamic memory allocation because thats not something i want to implement. 2.I suppose my input line oriented . 3.The maximum columns i need is 80 4.There is an infinite loop in the program :) 5.I have *not* tried to validate the data as yet.
9
2808
by: kardon33 | last post by:
Hi all, What i am trying to accomplish is take in a list of IP addresses from a text file (each Ip is on a new line). I got my program mostly working except when an IP address is longer than the last one it keeps the extra numbers beacuse im having trouble clearing the IP.
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7616
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.