🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.c.moderated
Article #2598

Re: fflush(stdin) - not guaranteed to work?

#2598
From: Maurizio Loreti
Date: Mon, 15 Apr 1996 18:09
43 lines
2442 bytes
In article <4ksjpn$rjt@solutions.solon.com>, gohel@csee.usf.edu (Himanshu Gohel) writes:
>In Paul S. Wang's "Introduction to ANSI C on UNIX" he says that
>the fflush() function was "not intended to control input buffering"
>on page 266.
>
>My question is, why?  Some of my students have written programs using
>fflush(stdin) hoping it would clear away anything that's in the input
>buffer before a scanf() statement and apparently it works on some PC
>based compilers, but when re-compiled on a UNIX system, it does not
>always work.

Apparently you missed Q/A 12.26 of the FAQ list,
RTFM.mit.edu:pub/usenet/comp.lang.c/*:

12.26:	How can I flush pending input so that a user's typeahead isn't
	read at the next prompt?  Will fflush(stdin) work?

A:	fflush() is defined only for output streams.  Since its
	definition of "flush" is to complete the writing of buffered
	characters (not to discard them), discarding unread input would
	not be an analogous meaning for fflush on input streams.

	There is no standard way to discard unread characters from a
	stdio input stream, nor would such a way be sufficient unread
	characters can also accumulate in other, OS-level input buffers.

	References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2; H&S Sec. 15.2.

>What is the best way to get rid of the '\n' from the input buffer after
>a scanf() statement?  In the same book on page 263 I've seen the following
>format used in an fscanf() format specifier:
>
> %*[\n]

The best way is to not use scanf at all :-)

Try fgets to read a whole line, if you want destroy the '\n' (if any!)
with an appropriate statement (the FAQ list in Q/A 7.1 suggests
  if((p = strchr(answer, '\n')) != NULL) *p = '\0';
), then parse appropriately the input line.
--
Maurizio Loreti                       http://mvxpd5.pd.infn.it/wwwcdf/mlo.html
Un. of Padova, Dept. of Physics - Padova, Italy          loreti@padova.infn.it
Technical Details
Message-ID: <4ku3d1$50s@solutions.solon.com>
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
References: <4ksjpn$rjt@solutions.solon.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
From: loreti@mxsld2.pd.infn.it (Maurizio Loreti)
Newsgroups: comp.lang.c.moderated,comp.lang.c
Subject: Re: fflush(stdin) - not guaranteed to work?
Date: 15 Apr 1996 13:09:37 -0500
Organization: I.N.F.N. Padova - CDF/CMS VAXcluster
Sender: clc@solutions.solon.com
Approved: clc@solutions.solon.com
Message-ID: <4ku3d1$50s@solutions.solon.com>
References: <4ksjpn$rjt@solutions.solon.com>
Reply-To: loreti@mxsld2.pd.infn.it
NNTP-Posting-Host: solutions.solon.com