473,426 Members | 1,620 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,426 software developers and data experts.

scanf behaviour

Hello.

I maybe reinvent the weel ...
I'm trying to read positive integer number with the help of scanf, if
the input value is not positive number but negaive one zero or char , i
have to reread the input until I get the needed pos. number

I wrote the code , but it doesn't work the way it should : if i put
some char into input, the program goes infinite loop instead of
promting me to enter a new value.

Please shed some light on what is the problem. thanks
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. int n;
  6. while (1)
  7. {
  8. printf("Please enter positive number \n");
  9. if ( scanf("%d",&n)!=1 || n<=0 )
  10. {
  11. printf("Illegal input!\n");
  12. continue;
  13. }
  14.  
  15. return 0;
  16. }
  17. return 1;
  18. }
  19.  
Nov 24 '06
68 4540
Simon Biber wrote:
CBFalconer wrote:
>It can be built around the routines I showed. The only problem is
with exponential notation, otherwise 1 char lookahead does fine.
The problem case is: "1.23ex" which requires 2 char lookahead, or 2
level ungetc. scanf suffers from this too.

scanf needs 3 char ungetc to handle "1.23e-x". The 'x', '-' and 'e'
are read and then put back into the buffer. The next character read
should be 'e'.
Unfortunately the C standard only guarantees one level, so this
action is impossible in portable code. It can't be grafted on
after the fact because any such graft would be ignored by all other
input routines.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Nov 28 '06 #51
Richard Heathfield <rj*@see.sig.invalidwrites:
Ian Collins said:
<snip>
>Just curious, has fflush( stdin ) always been undefined, rather than
implementation defined?

Yes.
>The Solaris version makes sense to me.

How can flushing input make sense? You flush toilets, not taps.
The Solaris version makes a fair amount of sense to me as well. C's
fflush() function doesn't *have* to follow the exact semantics of a
toilet.

In Solaris, fflush(stdin) discards any buffered input. If C defined a
discard_buffered_input() function, I don't think anyone would object
-- at least not on the same basis on which you object to
fflush(stdin). The C standard easily *could* have defined fflush() on
an input stream to work the way it does on Solaris. It just didn't.

One endpoint's input is often another endpoint's output; flushing
either makes an equal amount of sense, at least to me.

(And, if I recall correctly, "FLUSH(INPUT)" in UCSD Pascal did the
same thing as fflush(stdin) does in Solaris C; I used it regularly and
never had any problem with the name.)

fflush() on an input stream invokes undefined behavior because the C
standard says it does, and for no other reason. If you judge the
behavior of every standard C library function based on the meanings of
the English words that make up its name, you're going to run into
problems; it's not likely that your common sense will coincide with
that of the standard committee in every instance. (And even if it
did, many of the committee's decisions were based on existing
practice, not necessarily on common sense.)

fflush(stdin) invokes undefined behavior. Why? Because the standard
says so. Next!

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 28 '06 #52
Keith Thompson said:
C's fflush() function doesn't *have* to follow the exact semantics of a
toilet.
May I quote you? :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 28 '06 #53
Richard Heathfield <rj*@see.sig.invalidwrites:
Keith Thompson said:
>C's fflush() function doesn't *have* to follow the exact semantics of a
toilet.

May I quote you? :-)
You've already demonstrated that you can. In addition to that, you
certainly may (though it's a bit late for me to say otherwise).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 28 '06 #54
trm
Richard Heathfield wrote:
st******@gmail.com said:
I've tested "fflush( stdin );" on both WinXP and SunOS boxes
it works without a glitch.

Try driving on the wrong side of the road. That works without
a glitch too - mostly.
My drivers' manual claims this leads to undefined behaviour. But
I've tested it across both the Atlantic and the English Channel
and it works fine over there.

Nov 29 '06 #55
trm said:
Richard Heathfield wrote:
>st******@gmail.com said:
I've tested "fflush( stdin );" on both WinXP and SunOS boxes
it works without a glitch.

Try driving on the wrong side of the road. That works without
a glitch too - mostly.

My drivers' manual claims this leads to undefined behaviour.
It does.
But
I've tested it across both the Atlantic and the English Channel
and it works fine over there.
It works fine most places, most of the time - except of course for the one
time that it fatally doesn't. Undefined Behaviour - Just Say No.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 29 '06 #56

Richard Heathfield wrote:
Ian Collins said:

<snip>
I don't know about XP, but on Solaris fflush() on an input stream is
defined:

But in C, it isn't, and we discuss C here, not Solaris.
This non-standard behaviour probably goes back to pre-standard days

Unlikely. Do you have evidence to support that suggestion?
Why do you consider it unlikely? I think the most likely reason for an
implementation to define extensions of this sort to its applicable
standards is to support functionality which was defined before those
standards existed. That's the case here, but that's what I would have
expected.

Nov 29 '06 #57
J. J. Farrell said:
>
Richard Heathfield wrote:
>Ian Collins said:

<snip>
I don't know about XP, but on Solaris fflush() on an input stream is
defined:

But in C, it isn't, and we discuss C here, not Solaris.
This non-standard behaviour probably goes back to pre-standard days

Unlikely. Do you have evidence to support that suggestion?

Why do you consider it unlikely?
Call me Mr Cynical if you like, but I've seen plenty of probablys that
turned out to be ohmaybenots. If he knew himself to be right, he would not
have said "probably", and it is my experience that most people who guess
guess wrong. Hence "unlikely".

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 29 '06 #58
In article <-f******************************@bt.comrj*@see.sig.invalid writes:
J. J. Farrell said:
....
I don't know about XP, but on Solaris fflush() on an input stream is
defined:

But in C, it isn't, and we discuss C here, not Solaris.
Note that on Solaris it is not defined on all input streams. There are
some for which it is undefined, notably for the device where it is wanted
in most cases.
This non-standard behaviour probably goes back to pre-standard days

Unlikely. Do you have evidence to support that suggestion?
Why do you consider it unlikely?

Call me Mr Cynical if you like, but I've seen plenty of probablys that
turned out to be ohmaybenots. If he knew himself to be right, he would not
have said "probably", and it is my experience that most people who guess
guess wrong. Hence "unlikely".
In this case there is evidence that it comes from System V Unix. BSD
Unix did not have it. On the SunOS 4.1.3 manpage it is mentioned as
System V behaviour.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 29 '06 #59
av
On Tue, 28 Nov 2006 10:40:36 -0500, CBFalconer wrote:
>Simon Biber wrote:
>CBFalconer wrote:
>>It can be built around the routines I showed. The only problem is
with exponential notation, otherwise 1 char lookahead does fine.
The problem case is: "1.23ex" which requires 2 char lookahead, or 2
level ungetc. scanf suffers from this too.
scanf needs 3 char ungetc to handle "1.23e-x". The 'x', '-' and 'e'
are read and then put back into the buffer. The next character read
should be 'e'.
Unfortunately the C standard only guarantees one level, so this
action is impossible in portable code. It can't be grafted on
after the fact because any such graft would be ignored by all other
input routines.
i know i'm for you a ungly troll but what is the reason why it is not
possible (or 'good' for the standard C) to have a buffer of 256 chars
for FILE?

i remember i have a buffer of +-256 chars for FILE object and ungetc
if +-256 ungetc return fail

what is the problem with all this (have a buffer of 256 chars for FILE
object that all input/output function can to use)[oltre a non essere
"standard C"]? thank you

Nov 29 '06 #60
Keith Thompson <ks***@mib.orgwrote:
Richard Heathfield <rj*@see.sig.invalidwrites:
Ian Collins said:
Just curious, has fflush( stdin ) always been undefined, rather than
implementation defined?
Yes.
The Solaris version makes sense to me.
How can flushing input make sense? You flush toilets, not taps.

The Solaris version makes a fair amount of sense to me as well. C's
fflush() function doesn't *have* to follow the exact semantics of a
toilet.
Just as well; I wouldn't want my computer to sound like that every time
I write a line to a file.
In Solaris, fflush(stdin) discards any buffered input. If C defined a
discard_buffered_input() function, I don't think anyone would object
-- at least not on the same basis on which you object to
fflush(stdin).
Not entirely. However, I would still object, as I would also for
fflush(stdin), on the basis that discarding buffered input is not always
as easy as it seems. There's buffered and there's buffered; there are C
implementation buffers, and there are hardware buffers; IOW, it would
have to be quite strictly circumscribed to be implementable, and it's
not certain how useful such a limited flushing function would be.

Contrast this with an implementation-defined flushing function, which
can be useful for that implementation only, and ignore problems that
would occur on other hardware and/or OSes.

Richard
Nov 29 '06 #61

st******@gmail.com wrote:
I've tested "fflush( stdin );" on both WinXP and SunOS boxes it works
without a glitch.
Now try it on MacOS (classic and X), OS/2, AIX, HP-UX, Irix, OpenVMS,
MPE, OS-360, BeOS, embedded systems, etc., and tell us if it works
without a glitch on all of them.

The implementation doesn't define the language. An implementation
*may* choose to do something reasonable for fflush(stdin), but you
cannot rely on that being true for any arbitrary implementation.

Nov 29 '06 #62
In article <45****************@news.xs4all.nlrl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Keith Thompson <ks***@mib.orgwrote:
....
In Solaris, fflush(stdin) discards any buffered input. If C defined a
discard_buffered_input() function, I don't think anyone would object
-- at least not on the same basis on which you object to
fflush(stdin).
Note that if stdin is connected to a tty or a pipe, fflush is undefined
on Solaris! Solaris defines flushing an input stream only when it can
make sense, i.e. if is seekable (for instance a disk file).
Not entirely. However, I would still object, as I would also for
fflush(stdin), on the basis that discarding buffered input is not always
as easy as it seems. There's buffered and there's buffered; there are C
implementation buffers, and there are hardware buffers; IOW, it would
have to be quite strictly circumscribed to be implementable, and it's
not certain how useful such a limited flushing function would be.
Indeed.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 29 '06 #63
av
On Wed, 29 Nov 2006 15:48:01 +0100, av wrote:
>i know i'm for you a ungly troll but what is the reason why it is not
possible (or 'good' for the standard C) to have a buffer of 256 chars
for FILE?
i remember i have a buffer of +-256 chars for FILE object and ungetc
if +-256 ungetc return fail
what is the problem with all this (have a buffer of 256 chars for FILE
object that all input/output function can to use)[oltre a non essere
"standard C"]? thank you
i would like to say that the buffers that use get, fgetc and
almost all the input fuctions, buffers that are in the "FILE" struct
can be view (from me) in this way

-Size_buf 0 Size_buf
|----------|----------|

where at start "base" pointer point to "0".

if Size_buf>1 (like all my input-file-buffers) =ungetc can
unget more than 2 chars

where is the wrong in all this?
Yes i could unget chars that are not in the original file, but...

for input-output
i have to say i don't use fscanf, or scanf, and i use many
"specializzate" functions getline "like" (for get lines in many ways)
"specializzate" functions for get unsigned, int, double from FILEs
and a "sscanf" function.
for print i use printf like function
and sprintf like function (that use the len of buffer for not allow
programmer to write out of buffer)
Nov 29 '06 #64
On 28 Nov 2006 19:14:07 -0800, in comp.lang.c , "trm"
<tr****@yahoo.comwrote:
>Richard Heathfield wrote:
>st******@gmail.com said:
I've tested "fflush( stdin );" on both WinXP and SunOS boxes
it works without a glitch.

Try driving on the wrong side of the road. That works without
a glitch too - mostly.

My drivers' manual claims this leads to undefined behaviour. But
I've tested it across both the Atlantic and the English Channel
and it works fine over there.
You *drove* across the atlantic and the english channel? Wow, didn't
your carburettor flood?

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Nov 29 '06 #65
Mark McIntyre said:
On 28 Nov 2006 19:14:07 -0800, in comp.lang.c , "trm"
<tr****@yahoo.comwrote:
>>Richard Heathfield wrote:
>>st******@gmail.com said:

I've tested "fflush( stdin );" on both WinXP and SunOS boxes
it works without a glitch.

Try driving on the wrong side of the road. That works without
a glitch too - mostly.

My drivers' manual claims this leads to undefined behaviour. But
I've tested it across both the Atlantic and the English Channel
and it works fine over there.

You *drove* across the atlantic and the english channel? Wow, didn't
your carburettor flood?
<grinOkay, you're forgiven for the time being. That was worth it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 29 '06 #66
"Dik T. Winter" <Di********@cwi.nlwrites:
[...]
Keith Thompson <ks***@mib.orgwrote:
...
In Solaris, fflush(stdin) discards any buffered input. If C defined a
discard_buffered_input() function, I don't think anyone would object
-- at least not on the same basis on which you object to
fflush(stdin).

Note that if stdin is connected to a tty or a pipe, fflush is undefined
on Solaris! Solaris defines flushing an input stream only when it can
make sense, i.e. if is seekable (for instance a disk file).
[...]

I hadn't noticed that (I didn't pay a lot of attention to the man page
because I don't particularly need to flush input files).

What I had in mind was something I've done in the past (not in C),
namely:

Print a prompt for user input
Flush input
Read the user's response (from the keyboard)

The point of flushing input is to discard any characters the user
typed before the prompt appeared, for example if the user is familiar
enough with the program to type responses ahead of time, but the
prompt may not be one the user was expecting. (This was possible on
the systems I was using at the time; it may not be practical on more
modern systems.)

But apparently the Solaris fflush() doesn't support this usage. I'm
not sure what the point of flushing an input stream connected to a
disk file would be.

If flushing an input file does make sense on a given system, it should
probably be provided as a separate implementation-defined function.
The fact that Solaris extends an existing standard function causes
confusion. But I think we've established that Solaris does this for
backward compatibility with old SolOS systems that predate the ANSI C
standard (somebody mentioned SunOS 4.1.3, whose default C compiler was
pre-ANSI).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 29 '06 #67
In article <ln************@nuthaus.mib.orgKeith Thompson <ks***@mib.orgwrites:
"Dik T. Winter" <Di********@cwi.nlwrites:
....
Note that if stdin is connected to a tty or a pipe, fflush is undefined
on Solaris! Solaris defines flushing an input stream only when it can
make sense, i.e. if is seekable (for instance a disk file).
....
What I had in mind was something I've done in the past (not in C),
namely:

Print a prompt for user input
Flush input
Read the user's response (from the keyboard)

The point of flushing input is to discard any characters the user
typed before the prompt appeared, for example if the user is familiar
enough with the program to type responses ahead of time, but the
prompt may not be one the user was expecting. (This was possible on
the systems I was using at the time; it may not be practical on more
modern systems.)
Yes, but with modern systems it is barely possible to define such a function.
Especially when you are connected to a computer through a network. Should
the computer where the fflush is executed signal the computer from which it
receives its input to also do a fflush? It is possible when the user input
does not go through a whole lot of layers, and that is with modern computers
almost never the case.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 30 '06 #68
On 25 Nov 2006 00:28:03 GMT, jt@toerring.de (Jens Thoms Toerring)
wrote:
st******@gmail.com wrote:
I'm trying to read positive integer number with the help of scanf, if
the input value is not positive number but negaive one zero or char , i
have to reread the input until I get the needed pos. number
<snip better fgets case>
But since you're here just looking for a positive integer there's
the following alternative:
char buffer[10];
int x ;

do {
printf( "Please enter positive number\n" );
while ( scanf( "%9[^-+0-9]", buffer ) != 0 )
/* empty */ ;
Instead of a loop you can just do /*(void)*/scanf ("%*[-+0-9]");

But ranges like 0-9 in a %[ specifier are impl-def, so technically you
should spell out 0123456789 (or some permutation thereof).
} while ( scanf( "%d", &x ) != 1 || x <= 0 );
- David.Thompson1 at worldnet.att.net
Dec 18 '06 #69

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

Similar topics

5
by: Eduardo Olivarez | last post by:
The following code does not work correctly on my machine. Either one of the scanf()'s alone work perfectly. However, when they are combined, the second scanf() call just reads what the first one...
14
by: Peter Mount | last post by:
Hello I'm having trouble with " scanf("%c", &answer);" on line 20 below. When I run the program in cygwin on Windows 98SE it skips that line completely and ends the program. Does scanf have...
7
by: hugo27 | last post by:
obrhy8 June 18, 2004 Most compilers define EOF as -1. I'm just putting my toes in the water with a student's model named Miracle C. The ..h documentation of this compiler does state that when...
18
by: Radith | last post by:
HI all; I have created a program just to get an understanding of strcpy. (still an amateur developer). I use scanf("%s", &first) in order to get the input to the variable first (which is char...
33
by: Lalatendu Das | last post by:
Dear friends, I am getting a problem in the code while interacting with a nested Do-while loop It is skipping a scanf () function which it should not. I have written the whole code below. Please...
7
by: sajjanharudit | last post by:
Can anyone explain me what is happening in the following code: #include<stdio.h> int main() { int i,j; scanf("%d %d" + scanf("%d %d",&i,&j)); printf("%d %d\n"); }
30
by: James Daughtry | last post by:
char array; scanf("%19s", &array); I know this is wrong because it's a type mismatch, where scanf expects a pointer to char and gets a pointer to an array of 20 char. I know that question 6.12...
62
by: Argento | last post by:
I was curious at the start about how ungetc() returns the character to the stream, so i did the following coding. Things work as expected except if I change the scanf("%c",&j) to scanf("%d",&j). I...
27
by: guoliang | last post by:
help: #include<stdio.h> int main(void) { int a; char b; printf("int=");
3
by: Tinku | last post by:
#include<stdio.h> main() { char line; scanf("%", line); printf("%s", line); } it will read and print the line but what is "%" in general we gives %s, %c .
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
1
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.