473,654 Members | 2,990 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

peek at stdin, flush stdin

I'm trying to find a way to reliably peek at stdin, and if anything's
waiting, flush stdin so that it clears the stream ready to wait for a
character.

The problem I have is that in an application, if I call say scanf() to
get some input, occasionally the newline is still left hanging around in
the buffer. If there's any junk left over in stdin after getting input
I'd like to clear it out. And then when going to read input again
later, check for any junk and clear it out before prompting and
attempting to read input.

I've found a way to do this quite well by using:

scanf("%c%*c", &ch);

which gets a menu choice of a single character, and sucks up the newline
still in the stream. But, if any extra stuff is entered, this is not
very robust. It's all still left in the input stream. Because most of
my programs run in blocking mode, I can sit there in a loop and read
everything until stdin drains out. I've tried going into non-blocking
mode to "peek" at anything that might be there, get it, and then return,
but I couldn't make it work. It also seems like a bit of a nasty hack.

Any ideas?

Many thanks for your help.

Johnathan
Nov 14 '05 #1
4 15050
Johnathan Doe wrote:
I'm trying to find a way to reliably peek at stdin, and if anything's
waiting, flush stdin so that it clears the stream ready to wait for a
character.


char c;
scanf("%c%*[^\n]%*c", &c);

Should do the trick. It does not clear stdin if more than
one line was entered in some way.

--
Thomas.

Nov 14 '05 #2
>Johnathan Doe wrote:
I'm trying to find a way to reliably peek at stdin, and if anything's
waiting, flush stdin so that it clears the stream ready to wait for a
character.

In article <news:2g******* *****@uni-berlin.de>
Thomas stegen <ts*****@cis.st rath.ac.uk> suggests:char c;
scanf("%c%*[^\n]%*c", &c);

Should do the trick. It does not clear stdin if more than
one line was entered in some way.


Unfortunately, this technique does not work *unless* there is
at least one character other than newline following the one
desired input character. The reason is that the %[ directive
("%*[^\n]" => scan an unlimited length sequence of characters
other than newline, discarding each character scanned) fails
if the number of characters that match the scanset is zero.

In other words, scanning an input stream containing "y\n" puts the
'y' into c, then finds a newline and fails the %[ directive, and
then stops (and scanf() returns 1 -- one successful convert and
assign occurred). The newline remains in the stream. If the stream
contains "yes\n", on the other hand, the %c converts the 'y' as
desired, the %[ skips the 'e' and 's' as desired, than the %*c
discards the newline as desired. (Here scanf() again returns 1.)

The trick is to separate this into *two* scanf() calls:

r1 = scanf("%c%*[^\n]", &c);
r2 = scanf("%*c");

If it ever gets anything at all, the second scanf() just gets one
newline character, so it can be replaced with getchar(). The return
value from the first scanf() should be inspected first, to make
sure that the stream has not already hit end-of-file.

These all have a flaw: if the character stuck into "c" is a newline,
they read one more line, so you actually need *three* scanf() calls:

r1 = scanf("%c", &c);
... check for EOF and newline; if not ...
r2 = scanf("%*[^\n]"); /* read and discard all non-newlines */
if (r2 != EOF)
r3 = scanf("%*c"); /* then read and discard the newline */

A tiny function that calls getchar() in a loop may be more readable
to future programmers:

int get_one_letter_ response_on_a_l ine(void) {
int c, first;

/* get and save the first character */
first = c = getchar();

/* if it was not newline, keep getting more (but stop on EOF) */
while (c != '\n' && c != EOF)
c = getchar();

/* in any case, return the first one, which may be '\n' or EOF */
return first;
}

Now you can just have:

int c;
...
c = get_one_letter_ response_on_a_l ine();
switch (c) {
case 'y': case 'Y': /* handle "yes" */ break;
case 'n': case 'N': /* handle "no" */ break;
case EOF: /* handle EOF */ break;
default: puts("y(es) or n(o), please"); ...
}

for instance.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #3
Chris Torek wrote:

[snip]

WOW, thanks!!! :) :) :)

--
Johnathan

Nov 14 '05 #4
Thomas stegen wrote:

Thankyou for teaching me about [^\n] : it's not in my textbook!

Kind Regards.
char c;
scanf("%c%*[^\n]%*c", &c);

Should do the trick. It does not clear stdin if more than
one line was entered in some way.


Nov 14 '05 #5

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

Similar topics

30
45791
by: Jonathan Neill | last post by:
I'm aware that there is no ANSI (or POSIX, or any standard, to my knowledge) way of flushing stdin or any other application-level input buffer, but if anyone knows a hack or a non-portable way to do this, no matter how obscure or arcane, I'd appreciate it.
3
10145
by: Fernando Arbeiza | last post by:
Hi: I need some clarification about a code like this: printf("%s", "a string with NO trailing newline"); scanf("%d", &i); Regarding if a fflush() of the standard output is needed or not. I think the relevant portions of the standard are:
11
14628
by: Darklight | last post by:
is this correct or incorrect i just read the post below before posting this: In fflush(stdin), what happens to flushed data? this program is taken from sams teach yourself c in 21 days /* LIST13-6.C CLEARING STDIN OF EXTRA CHARACTERS */ /* USING FFLUSH() FUNCTION */ #include<stdio.h> int main(void)
0
8375
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
8290
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
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8707
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...
0
8593
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7306
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
2714
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
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
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.