473,395 Members | 1,969 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,395 software developers and data experts.

how to check the scanf function if it will read more than one number

my code:
do
{
printf("please input the dividend and the divisor.\n");
if(!scanf("%d%d",&dend,&dor))
{
temp1=1;
fflush(stdin);
}
else
temp1=0;
}while(temp1==1);

it seems that it only depend on the first number it read.
if I input " a 32 ", it could know there is a error,
but if I input " 32 a ",
it accept that.

thanks in advance.

Jan 2 '06 #1
51 3813

moosdau wrote:
my code:
do
{
printf("please input the dividend and the divisor.\n");
if(!scanf("%d%d",&dend,&dor))
{
temp1=1;
fflush(stdin);
}
else
temp1=0;
}while(temp1==1);

it seems that it only depend on the first number it read.
if I input " a 32 ", it could know there is a error,
but if I input " 32 a ",
it accept that.

thanks in advance.

Hi,

In "man scanf", I suggest you to read chapter "return values".

Kind regards.

Jan 2 '06 #2
do you mean the linux os?
but I'm using windows,so I can't use the "man" command.
could you tell me plz?

Jan 2 '06 #3
moosdau wrote:
do you mean the linux os?
but I'm using windows,so I can't use the "man" command.
could you tell me plz?

For windows, look up the function at
http://msdn.microsoft.com/

(A little hint is that scanf returns the nr of successfully
assigned items)
Jan 2 '06 #4
"moosdau" <mo*****@gmail.com> writes:
my code:
do
{
printf("please input the dividend and the divisor.\n");
if(!scanf("%d%d",&dend,&dor))
{
temp1=1;
fflush(stdin);
}
else
temp1=0;
}while(temp1==1);

it seems that it only depend on the first number it read.
if I input " a 32 ", it could know there is a error,
but if I input " 32 a ",
it accept that.


scanf() returns the number of items assigned. If you give it " 32 a ",
it will assign 32 to dend and fail to assign a value to dor; scanf()
will then return 1. If you want to assign both values, you need to
check whether scanf() returned 2.

You should pick a better name than "temp1". The simplest thing to do
is to assign the result of scan() to a variable, and test the value
of that variable. Pseudo-code follows:

do {
printf("...\n");
items_read = scanf(...);
} while (items_read != 2);

Don't use fflush(stdin). The fflush() function is defined only for
output streams.

scanf() can be very tricky, it can leave unread garbage in your input
stream, and it can be difficult to figure out just what it's doing. A
better approach is to use fgets() to read an entire line, then use
sscanf() to get information from the line you've read.

--
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.
Jan 2 '06 #5

moosdau wrote:
do you mean the linux os?
but I'm using windows,so I can't use the "man" command.
could you tell me plz?


Mna pages are also available in hundreds of www servers.

Jan 2 '06 #6
moosdau wrote:

do you mean the linux os? but I'm using windows,so I can't use
the "man" command. could you tell me plz?


Include context. Without it we have no idea what you mean. See my
sig, and the reference therein, for how to do this.

On Windoze you are probably either using Microsoft VC, or some port
of GCC. With the gcc versions you very likely have info (the
command) available, especially if you have installed DJGPP or
Cygwin. Otherwise the VC help system will probably lead you to a
discussion of scanf.

On this windoze system the command:

C>info libc alpha scanf

brings up a screen that begins as follows:

scanf
=====

Syntax
------

#include <stdio.h>

int scanf(const char *format, ...);

Description
-----------

This function scans formatted text from `stdin' and stores it in
the variables pointed to by the arguments. *Note scanf::.
.... and so forth ...

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 2 '06 #7

Keith Thompson wrote:
scanf() returns the number of items assigned. If you give it " 32 a ",
it will assign 32 to dend and fail to assign a value to dor; scanf()
will then return 1. If you want to assign both values, you need to
check whether scanf() returned 2.

You should pick a better name than "temp1". The simplest thing to do
sorry,because I copied it from a long code,
if I named every variant with its meaning, there must be too many
temporary variants.
so ......
is to assign the result of scan() to a variable, and test the value
of that variable. Pseudo-code follows:

do {
printf("...\n");
items_read = scanf(...);
} while (items_read != 2);

Don't use fflush(stdin). The fflush() function is defined only for
output streams.

Thanks very much!!
but I don't know very clearly why shouldn't I use the fflush function.
if there is not any usable data in the input stream,
could I use it to clear the input stream?
if not , could you please tell me why?

scanf() can be very tricky, it can leave unread garbage in your input
stream, and it can be difficult to figure out just what it's doing. A
better approach is to use fgets() to read an entire line, then use
sscanf() to get information from the line you've read.
thanks for your suggestion!

--
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.


Jan 2 '06 #8
moosdau said:

<snip>
[...] I don't know very clearly why shouldn't I use the fflush function.
if there is not any usable data in the input stream,
Because fflush's behaviour is only defined for streams open for output or
update.
could I use it to clear the input stream?
Not as far as the C language is concerned, no.
if not , could you please tell me why?


For the same reason that pressing the handle on your toilet will not get rid
of the water waiting in your sink's tap (or faucet, if you're on that side
of the pond). Flushing is something we do to output, not to input.

If you want to discard from stdin everything up to and including a
particular character, you can use this function:

#include <stdio.h>

int DiscardFromStream(FILE *fp, int lim)
{
int ch;
while((ch = getc(fp)) != lim && ch != EOF)
{
continue;
}
return ch == EOF;
}

/* example usage */
int main(void)
{
int ch;
puts("Type a letter, and press ENTER.");
ch = getchar();
if(0 == DiscardFromStream(stdin, '\n'))
{
printf("You pressed %c\n", ch);
puts("Type another letter, and press ENTER.");
ch = getchar();
if(0 == DiscardFromStream(stdin, '\n'))
{
printf("You pressed %c\n", ch);
}
}
return 0;
}

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 2 '06 #9

"moosdau" <mo*****@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...

Thanks very much!!
but I don't know very clearly why shouldn't I use the fflush function.
if there is not any usable data in the input stream,
could I use it to clear the input stream?
if not , could you please tell me why?


There's no easy way to purge stdin, esp when it's already potentially empty,
i.e., most [all that I can think of right now] std functions that could
potentially test for this will *wait* if stdin is empty, e.g., getchar,
scanf, gets, fgets, feof, ... it's a toughie, and I would suggest that, *if*
your code need *not* be portable, and *if* your implementation of fflush
works on stdin ok, well, you should perhaps stick with it then! I'll get
flamed for suggesting this of course - or - better still, someone will come
up with a portable way to flush stdin ;-)

Jan 2 '06 #10
pemo said:
I would suggest
that, *if* your code need *not* be portable, and *if* your implementation
of fflush works on stdin ok, well, you should perhaps stick with it then!
Bad advice. Better to avoid the problem completely, which is trivial.
I'll get flamed for suggesting this of course - or - better still,
someone will come up with a portable way to flush stdin ;-)


That doesn't make sense, since flushing is not something we do to input.
I've already posted a portable way to discard characters from stdin until a
delimiter is encountered.

I never, ever have to solve this problem in my own code, because I capture
all text input a line at a time. Why don't you just do that too?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 2 '06 #11
moosdau wrote:
Keith Thompson wrote:
scanf() returns the number of items assigned. If you give it " 32 a ",
it will assign 32 to dend and fail to assign a value to dor; scanf()
will then return 1. If you want to assign both values, you need to
check whether scanf() returned 2.

You should pick a better name than "temp1". The simplest thing to do


sorry,because I copied it from a long code,
if I named every variant with its meaning, there must be too many
temporary variants.
so ......


If that is a problem it sounds like your function is too long and it
should be split in to multiple functions.
is to assign the result of scan() to a variable, and test the value
of that variable. Pseudo-code follows:

do {
printf("...\n");
items_read = scanf(...);
} while (items_read != 2);

Don't use fflush(stdin). The fflush() function is defined only for
output streams.


Thanks very much!!
but I don't know very clearly why shouldn't I use the fflush function.
if there is not any usable data in the input stream,
could I use it to clear the input stream?
if not , could you please tell me why?


<snip>

You should not use it in input streams because it is not defined. That
means anything can happen, from what you expect to your computer growing
arms and hands and punching you in the nose. More likely effects, if it
appears to work on your current system, are you doing an update and it
suddenly not doing what you expect but either doing nothing or giving
some kind of access violation error.

If you want to clear the input stream you have to decide on what you
mean, possibly reading the rest of the line, and do that. If you really
do want to throw away anything the user has typed so far (what if input
is piped in from a file though!) and get the next thing the user types,
then you can't do that in standard C and will have to use system
specific routines.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 2 '06 #12

"Richard Heathfield" <in*****@invalid.invalid> wrote in message
news:dp**********@nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com...
pemo said:
I would suggest
that, *if* your code need *not* be portable, and *if* your implementation
of fflush works on stdin ok, well, you should perhaps stick with it then!
Bad advice. Better to avoid the problem completely, which is trivial.


But, I'd wager, not as trivial as scanf("%d", &n); fflush(stdin); if it were
fully supported? Aren't you talkig about something like this?

char buffer[100];

int n;

if(fgets(buffer, sizeof(buffer), stdin))
{
if(sscanf(buffer, "%d", &n))
{
printf("w00t, we read an int! (%d)\n", n);
}
}
I'll get flamed for suggesting this of course - or - better still,
someone will come up with a portable way to flush stdin ;-)


That doesn't make sense, since flushing is not something we do to input.
I've already posted a portable way to discard characters from stdin until
a
delimiter is encountered.


I know what you mean [the 'logic' of it], but as this scanf type question is
often asked here, it obviously does make sense in that context - e.g., since
scanf is provided, and as that function is invariably the function that's
used in tutorials, it *would* make sense [surely?] to have some way of
removing any unread characters held in the stdin stream?
I never, ever have to solve this problem in my own code, because I capture
all text input a line at a time. Why don't you just do that too?


Sure, it's a good way to handle the problem, but see my wager.

Jan 2 '06 #13
pemo wrote:
.... snip ...
I know what you mean [the 'logic' of it], but as this scanf type
question is often asked here, it obviously does make sense in
that context - e.g., since scanf is provided, and as that
function is invariably the function that's used in tutorials, it
Not in good tutorials.
*would* make sense [surely?] to have some way of removing any
unread characters held in the stdin stream?


We do. My variant of Richards function is:

int flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
return ch;
}

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 2 '06 #14

"Chuck F. " <cb********@yahoo.com> wrote in message
news:R7********************@maineline.net...
pemo wrote:

... snip ...

I know what you mean [the 'logic' of it], but as this scanf type
question is often asked here, it obviously does make sense in
that context - e.g., since scanf is provided, and as that
function is invariably the function that's used in tutorials, it


Not in good tutorials.


I didn't think that there were any????
*would* make sense [surely?] to have some way of removing any
unread characters held in the stdin stream?


We do. My variant of Richards function is:

int flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
return ch;
}


Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}
Jan 2 '06 #15
moosdau a écrit :
do you mean the linux os?
but I'm using windows,so I can't use the "man" command.
could you tell me plz?


google 'man <item>' works too...

--
A+

Emmanuel Delahaye
Jan 2 '06 #16
pemo a écrit :
There's no easy way to purge stdin, esp when it's already potentially empty,
i.e., most [all that I can think of right now] std functions that could
potentially test for this will *wait* if stdin is empty, e.g., getchar,
scanf, gets, fgets, feof, ... it's a toughie, and I would suggest that, *if*
your code need *not* be portable, and *if* your implementation of fflush
works on stdin ok, well, you should perhaps stick with it then! I'll get
flamed for suggesting this of course - or - better still, someone will come
up with a portable way to flush stdin ;-)


It's a design issue. Using the proper input function in the proper way
avoids these problems of pending characters. The canonic way :

char line[PROPER_SIZE];

if (fgets(line, sizeof line, stdin) != NULL)
{
/* search */
char *p = strchr(line, '\n');
if (p != NULL)
{
/* kill */
*p = 0;
}
else
{
/* purge */
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF)
{
}
}
}

stick this into some getline() function of your own, add the required
headers (<stdio.h> and <string.h>) and you have a decent input function
for life.

--
A+

Emmanuel Delahaye
Jan 2 '06 #17
"pemo" <us***********@gmail.com> writes:
"Chuck F. " <cb********@yahoo.com> wrote in message
news:R7********************@maineline.net...

[...]
We do. My variant of Richards function is:

int flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
return ch;
}


Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}


What if getchar() returns EOF before returning '\n'?

Note that there are two different things being discussed here. One,
which is easily implementable in standard C, is discarding all the
remaining characters in a line. The other, which can't be done in
standard C, is discarding all typed characters that haven't been
processed yet, i.e., flushing the typeahead buffer.

I think the former is what the OP really wants.

--
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.
Jan 2 '06 #18

"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"pemo" <us***********@gmail.com> writes:
"Chuck F. " <cb********@yahoo.com> wrote in message
news:R7********************@maineline.net...

[...]
We do. My variant of Richards function is:

int flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
return ch;
}


Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}


What if getchar() returns EOF before returning '\n'?


Surely, if there's a \n in the buffer, getchar won't return EOF?

If there's not a \n in the buffer, I can see that testing for EOF might be a
good idea.
Jan 2 '06 #19
pemo a écrit :
Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}


No, because stdin can be redirected from a file. EOF must be checked too.

Note that the 'return;' is useless.

--
A+

Emmanuel Delahaye
Jan 2 '06 #20
pemo a écrit :
Not in good tutorials.


I didn't think that there were any????


http://publications.gbdirect.co.uk/c_book/

--
A+

Emmanuel Delahaye
Jan 2 '06 #21
pemo wrote:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"pemo" <us***********@gmail.com> writes:
"Chuck F. " <cb********@yahoo.com> wrote in message
news:R7********************@maineline.net...

[...]
We do. My variant of Richards function is:

int flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
return ch;
}
Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}

What if getchar() returns EOF before returning '\n'?


Surely, if there's a \n in the buffer, getchar won't return EOF?

If there's not a \n in the buffer, I can see that testing for EOF might be a
good idea.


Yes, but how do you know if there is (or ever will be) a \n in the input
buffer? Some systems allow the last line of a file to not be terminated
by a line feed, and some systems allow you to redirect a file to
standard input. Combine those two and you have an obvious mechanism for
reaching the end of file before reaching a \n even with stdin.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 2 '06 #22
"pemo" <us***********@gmail.com> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"pemo" <us***********@gmail.com> writes: [...]
Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}


What if getchar() returns EOF before returning '\n'?


Surely, if there's a \n in the buffer, getchar won't return EOF?

If there's not a \n in the buffer, I can see that testing for EOF might be a
good idea.


So perhaps you should do something like this:

void flushstdin(void)
{
if (theres_a_newline_in_the_buffer()) {
while(getchar() != '\n')
;
}
else {
int c;
while(c = getchar(), c != '\n' && c != EOF)
;
}
}

Implementing the theres_a_newline_in_the_buffer() function in portable
C is left as an exercise. If you can't think of a way to do it,
perhaps you should just test for EOF.

To answer my own question from upthread, if you reach EOF on stdin
before seeing a '\n' character, your flushstdin() function becomes an
infinite loop; getchar() will repeatedly return EOF, and the condition
will never allow the loop to terminate.

--
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.
Jan 2 '06 #23
Emmanuel Delahaye <em***@YOURBRAnoos.fr> writes:
pemo a écrit :
Would this be acceptable for stdin?
void flushstdin(void)
{
while(getchar() != '\n')
;
return;
}


No, because stdin can be redirected from a file. EOF must be checked too.


It's not just because stdin can be redirected from a file. EOF can
occur before the end of a line, at least on some systems. (On
Unix-like systems, if you're reading from the keyboard, hitting
control-D twice in the middle of a line generally does this.)

--
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.
Jan 2 '06 #24
Emmanuel Delahaye said:
Note that the 'return;' is useless.


Only to the compiler.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 2 '06 #25
pemo wrote:
"Chuck F. " <cb********@yahoo.com> wrote in message
.... snip ...
*would* make sense [surely?] to have some way of removing any
unread characters held in the stdin stream?


We do. My variant of Richards function is:

int flushln(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (('\n' != ch) && (EOF != ch));
return ch;
}


Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}


No, it doesn't handle EOF. However, if you have flushln available
you can write:

#define flushstdin flushln(stdin)

although I don't know why you would bother.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 3 '06 #26
Keith Thompson wrote:
.... snip ...
Note that there are two different things being discussed here.
One, which is easily implementable in standard C, is discarding
all the remaining characters in a line. The other, which can't
be done in standard C, is discarding all typed characters that
haven't been processed yet, i.e., flushing the typeahead buffer.

I think the former is what the OP really wants.

True. However, lacking the latter, use of the former requires that
one keep track of what routines flush to end of line. For example,
fgets doesn't necessarily, which can make usage awkward. gets (to
Newbies - which is never to be used) does, whilst destroying your
system. The scanf family doesn't, because they put the field
terminating char back in the input stream. My ggets does. The
various bufferless input routines I have published here don't (they
push back the terminating char).

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 3 '06 #27
Richard Heathfield <in*****@invalid.invalid> writes:
Emmanuel Delahaye said:
Note that the 'return;' is useless.


Only to the compiler.


Implying that it's useful to the reader? This was a "return;" at the
very end of a void function; how is that useful at all?

--
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.
Jan 3 '06 #28

Richard Heathfield wrote:
For the same reason that pressing the handle on your toilet will not get rid
of the water waiting in your sink's tap (or faucet, if you're on that side
of the pond). Flushing is something we do to output, not to input.


thanks.
but what I want to know is the "actual" reason,
not a "logical" one.
e.g.
void f( int*p )
{
if (p->num)
do something;
}
when this function is running, there will be an error.
if I don't know the reason,what I want to know is :
if p is a NULL pointer, p->num will cause the error.

so ,the fflush function works very well on my computer now,
If it cause a potential danger,
I want to know what is it, and what is the condition.
if possible, an example is the best. :)

thanks for all !

Jan 3 '06 #29
Moosdau wrote:
Richard Heathfield wrote:
For the same reason that pressing the handle on your toilet will not get rid
of the water waiting in your sink's tap (or faucet, if you're on that side
of the pond). Flushing is something we do to output, not to input.
thanks.
but what I want to know is the "actual" reason,
not a "logical" one.


The "actual" reason is that the C language standard does not define
a behaviour for fflush() on an input stream.
e.g.
void f( int*p )
{
if (p->num)
do something;
}
when this function is running, there will be an error.
if I don't know the reason,what I want to know is :
if p is a NULL pointer, p->num will cause the error.

so ,the fflush function works very well on my computer now,
Your implementation probably defines a behaviour fflush on
input streams. It would do so as an extension. That extension
is not topical in comp.lang.c.
If it cause a potential danger,
I want to know what is it, and what is the condition.
if possible, an example is the best. :)


void g(FILE *fp)
{
fflush(fp);
}

If fp is purely an input stream, this invokes undefined behaviour. In
other
words, it's as dangerous as f() above.

--
Peter

Jan 3 '06 #30

Peter Nilsson wrote:
Your implementation probably defines a behaviour fflush on
input streams. It would do so as an extension. That extension
is not topical in comp.lang.c.

it do be that.
I think I've already known the answer.
the below is I copied from MSDN:

The fflush function flushes a stream. If the file associated with
stream is open for output, fflush writes to that file the contents of
the buffer associated with the stream.
If the stream is open for input, fflush clears the contents of the
buffer.

Example
// crt_fflush.c
#include <stdio.h>
#include <conio.h>

int main( void )
{
int integer;
char string[81];

/* Read each word as a string. */
printf( "Enter a sentence of four words with scanf: " );
for( integer = 0; integer < 4; integer++ )
{
scanf( "%s", string );
// Security caution!
// Beware allowing user to enter data directly into a buffer
// without checking for buffer overrun possiblity.
printf( "%s\n", string );
}

/* You must flush the input buffer before using gets. */
fflush( stdin ); // fflush on input stream is an extension to the
C standard
printf( "Enter the same sentence with gets: " );
gets( string );
printf( "%s\n", string );
}
Input
This is a test
This is a test
Sample Output
Enter a sentence of four words with scanf: This is a test
This
is
a
test
Enter the same sentence with gets: This is a test
This is a test
then I know,I shouldn't use fflush(stdin) except in VC.
but in VC, it is safe.

thanks to all again !

Jan 3 '06 #31
"Moosdau" <mo*****@gmail.com> writes:
Peter Nilsson wrote:
Your implementation probably defines a behaviour fflush on
input streams. It would do so as an extension. That extension
is not topical in comp.lang.c.
it do be that.
I think I've already known the answer.
the below is I copied from MSDN:

The fflush function flushes a stream. If the file associated with
stream is open for output, fflush writes to that file the contents of
the buffer associated with the stream.
If the stream is open for input, fflush clears the contents of the
buffer.

Example
// crt_fflush.c
#include <stdio.h>
#include <conio.h>

int main( void )
{

[snip] int integer;
char string[81];

/* Read each word as a string. */
printf( "Enter a sentence of four words with scanf: " );
for( integer = 0; integer < 4; integer++ )
{
scanf( "%s", string );
// Security caution!
// Beware allowing user to enter data directly into a buffer
// without checking for buffer overrun possiblity.
printf( "%s\n", string );
}
So MSDN shows an example of a possible buffer overflow and provides a
comment that doesn't give you a clue how to avoid it.
/* You must flush the input buffer before using gets. */
fflush( stdin ); // fflush on input stream is an extension to the
C standard
printf( "Enter the same sentence with gets: " );
gets( string );
printf( "%s\n", string );
}
And the example uses gets() without even warning that it's unsafe.
For nearly all practical purposes, gets() cannot be used safely.

[snip]
then I know,I shouldn't use fflush(stdin) except in VC.
but in VC, it is safe.


Here's a better idea: don't use fflush(stdin) at all. Second best:
don't use fflush(stdin) unless you're certain your code will never be
ported to an implementation that doesn't support it.

--
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.
Jan 3 '06 #32
Moosdau wrote:
Peter Nilsson wrote:
Your implementation probably defines a behaviour fflush on
input streams. It would do so as an extension. That extension
is not topical in comp.lang.c.

it do be that. I think I've already known the answer. the below
is I copied from MSDN:

The fflush function flushes a stream. If the file associated
with stream is open for output, fflush writes to that file the
contents of the buffer associated with the stream. If the stream
is open for input, fflush clears the contents of the buffer.


Which is typical of Microsoft ignoring standards. They encourage
people to write non-standard code, which is then tied to their own
systems, and thus increases their income.

For general systems where what, if anything, functions as an input
mechanism is not defined, the C language has no control. There is
no way it can possibly anticipate the arrival of input. Thus input
routines, when called, have to await actual input before returning.
There may not be any input buffer, and if there is there is no
defined way of interrogating it for non-emptyness. Thus the
language cannot insist on fflush functioning on input streams, and
any attempt to so do makes the program non-portable.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 3 '06 #33
Keith Thompson said:
Richard Heathfield <in*****@invalid.invalid> writes:
Emmanuel Delahaye said:
Note that the 'return;' is useless.


Only to the compiler.


Implying that it's useful to the reader? This was a "return;" at the
very end of a void function; how is that useful at all?


It's a tiny, tiny advantage, but an advantage nonetheless, at least to me.

My functions generally have one entry point and one exit point. The exit
point is the return statement. So I'm accustomed to writing one in each
function, generally as the /last/ line typed in the first cut of the
function. (The closing brace is typed immediately after the opening brace,
to save me from encountering pairing-up nonsenses later.)

So, when I see a function with no return statement, I find myself thinking
"is this function finished yet?"

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 3 '06 #34
Moosdau said:

Richard Heathfield wrote:
For the same reason that pressing the handle on your toilet will not get
rid of the water waiting in your sink's tap (or faucet, if you're on that
side of the pond). Flushing is something we do to output, not to input.
thanks.
but what I want to know is the "actual" reason,
not a "logical" one.


I gave you both in my previous reply; as well as the text you quote above, I
also wrote: "Because fflush's behaviour is only defined for streams open
for output or update." That is the actual reason.
if p is a NULL pointer, p->num will cause the error.
The C Standard assures us the code is wrong to dereference a null pointer,
but it does not specify that there will be "an error". It only says the
behaviour is undefined.
so ,the fflush function works very well on my computer now,
That's nice.
If it cause a potential danger,
If you use it in a way it was never intended to be used, that's a potential
danger.
I want to know what is it, and what is the condition.
if possible, an example is the best. :)


Okay, here's an example. Let's say you choose to use fflush(stdin) because
Microsoft say it's okay, and then in five years time Microsoft goes bust
and everyone starts using Macs instead, and you port your code to a Mac and
suddenly it stops working, and the reason it stops working is that you
thought "MSDN" was an acceptable substitute for "The ISO C Standard" and
wrote your code on that basis. Well, if you want to create unnecessary
portability headaches for yourself, that's your lookout.

The irony is that this is such a pointless discussion, since you simply
don't /need/ to "flush" input. Well, I don't, anyway, and I do a /lot/ of
text processing in C.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 3 '06 #35

Richard Heathfield wrote:
Okay, here's an example. Let's say you choose to use fflush(stdin) because
Microsoft say it's okay, and then in five years time Microsoft goes bust
and everyone starts using Macs instead, and you port your code to a Mac and
suddenly it stops working, and the reason it stops working is that you
thought "MSDN" was an acceptable substitute for "The ISO C Standard" and
wrote your code on that basis. Well, if you want to create unnecessary
portability headaches for yourself, that's your lookout.
haha !
The irony is that this is such a pointless discussion, since you simply
don't /need/ to "flush" input. Well, I don't, anyway, and I do a /lot/ of
text processing in C.
but ,seriously , if the ISO can provide a compiler that obey it's
standard absolutely,
how cool will that be!
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


Jan 3 '06 #36
In article <11**********************@g43g2000cwa.googlegroups .com> "Moosdau" <mo*****@gmail.com> writes:
Richard Heathfield wrote:
For the same reason that pressing the handle on your toilet will not
get rid of the water waiting in your sink's tap (or faucet, if you're
on that side of the pond). Flushing is something we do to output, not
to input.


thanks.
but what I want to know is the "actual" reason,
not a "logical" one.


It is not well-defined in general what flushing the input stream means.
Especially when you are connected through a network. Does it mean
discarding all input that has arrived at the computer where the
program is running? Does it mean discarding also all input that is
still somewhere on the way on the network? And if so how does the
system know what was already on the way when fflush was called and
what was not yet on the way?
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Jan 3 '06 #37

"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"pemo" <us***********@gmail.com> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"pemo" <us***********@gmail.com> writes: [...] Would this be acceptable for stdin?

void flushstdin(void)
{
while(getchar() != '\n')
;

return;
}

What if getchar() returns EOF before returning '\n'?


Surely, if there's a \n in the buffer, getchar won't return EOF?

If there's not a \n in the buffer, I can see that testing for EOF might
be a
good idea.


So perhaps you should do something like this:

void flushstdin(void)
{
if (theres_a_newline_in_the_buffer()) {
while(getchar() != '\n')
;
}
else {
int c;
while(c = getchar(), c != '\n' && c != EOF)
;
}
}

Implementing the theres_a_newline_in_the_buffer() function in portable
C is left as an exercise. If you can't think of a way to do it,
perhaps you should just test for EOF.

To answer my own question from upthread, if you reach EOF on stdin
before seeing a '\n' character, your flushstdin() function becomes an
infinite loop; getchar() will repeatedly return EOF, and the condition
will never allow the loop to terminate.


Ok, point taken.
Jan 3 '06 #38

"Richard Heathfield" <in*****@invalid.invalid> wrote in message
news:dp**********@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com...
Keith Thompson said:
Richard Heathfield <in*****@invalid.invalid> writes:
Emmanuel Delahaye said:

Note that the 'return;' is useless.

Only to the compiler.


Implying that it's useful to the reader? This was a "return;" at the
very end of a void function; how is that useful at all?


It's a tiny, tiny advantage, but an advantage nonetheless, at least to me.

My functions generally have one entry point and one exit point. The exit
point is the return statement. So I'm accustomed to writing one in each
function, generally as the /last/ line typed in the first cut of the
function. (The closing brace is typed immediately after the opening brace,
to save me from encountering pairing-up nonsenses later.)

So, when I see a function with no return statement, I find myself thinking
"is this function finished yet?"


It's the same with me - plus - [and it's a similar point] I also have a
personal problem with being as explicit as possible - in that I always try
to be!
Jan 3 '06 #39

"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> wrote in message
news:43**********************@nan-newsreader-06.noos.net...
pemo a écrit :
Not in good tutorials.


I didn't think that there were any????


http://publications.gbdirect.co.uk/c_book/


Any other testimonials for this?
Jan 3 '06 #40
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
No, it doesn't handle EOF. However, if you have flushln available
you can write:

#define flushstdin flushln(stdin)
I've never heard of flushln - what systems does it exist on?
although I don't know why you would bother.

Jan 3 '06 #41
Jordan Abel <ra*******@gmail.com> writes:
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
#define flushstdin flushln(stdin)

I've never heard of flushln - what systems does it exist on?


Read before answering.

DES
--
Dag-Erling Smørgrav - de*@des.no
Jan 3 '06 #42
Jordan Abel wrote:
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
No, it doesn't handle EOF. However, if you have flushln
available you can write:

#define flushstdin flushln(stdin)


I've never heard of flushln - what systems does it exist on?
although I don't know why you would bother.


All you had to do was read this thread. I have published at least
two realizations of flushln in it.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 3 '06 #43

"Chuck F. " <cb********@yahoo.com> wrote in message
news:F9********************@maineline.net...
Jordan Abel wrote:
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
No, it doesn't handle EOF. However, if you have flushln
available you can write:

#define flushstdin flushln(stdin)


I've never heard of flushln - what systems does it exist on?
although I don't know why you would bother.


All you had to do was read this thread. I have published at least two
realizations of flushln in it.


But, you know what's what here: if your comment doesn't appear with
[verbose] context, you're *****
Jan 3 '06 #44
Chuck F. said:
Jordan Abel wrote:
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
>
No, it doesn't handle EOF. However, if you have flushln
available you can write:

#define flushstdin flushln(stdin)


I've never heard of flushln - what systems does it exist on?
although I don't know why you would bother.


All you had to do was read this thread. I have published at least
two realizations of flushln in it.


Usenet is an asynchronous medium. Please don't assume that everybody has
been able to read all previous articles in a thread. It is generally easy
to skip around this problem; for example, you could have said:

"However, if you use flushln() available on your system (source for the
fflushln function is provided upthread) you can write..."

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 3 '06 #45
Richard Heathfield wrote:
Chuck F. said:
Jordan Abel wrote:
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:

No, it doesn't handle EOF. However, if you have flushln
available you can write:

#define flushstdin flushln(stdin)

I've never heard of flushln - what systems does it exist on?
although I don't know why you would bother.


All you had to do was read this thread. I have published at
least two realizations of flushln in it.


Usenet is an asynchronous medium. Please don't assume that
everybody has been able to read all previous articles in a
thread. It is generally easy to skip around this problem; for
example, you could have said:

"However, if you use flushln() available on your system (source
for the fflushln function is provided upthread) you can
write..."

He's even more careless than that. One of the flushln
implementations was quoted in the article to which he replied, and
he snipped it! So there is no doubt he saw it.

Maybe he is one of the Wikipedia editors who are amusing you?

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 3 '06 #46
Moosdau wrote
(in article
<11**********************@g43g2000cwa.googlegroups .com>):

Richard Heathfield wrote:
For the same reason that pressing the handle on your toilet will not get rid
of the water waiting in your sink's tap (or faucet, if you're on that side
of the pond). Flushing is something we do to output, not to input.
thanks.
but what I want to know is the "actual" reason,
not a "logical" one.


I think you will find that quite often (apart from understanding
the behavior of Wives and a few other exceptions) that the
"logical" one turns out to be the "actual" one.
e.g.
void f( int*p )
{
if (p->num)
do something;
}
when this function is running, there will be an error.
if I don't know the reason,what I want to know is :
if p is a NULL pointer, p->num will cause the error.
That is only one possible reason. There are other ways it could
fail, without a NULL pointer.
so ,the fflush function works very well on my computer now,
If it cause a potential danger,
I want to know what is it, and what is the condition.
if possible, an example is the best. :)


Because the standard says so. Actual enough for you?


--
Randy Howard (2reply remove FOOBAR)
"The power of accurate observation is called cynicism by those
who have not got it." - George Bernard Shaw

Jan 3 '06 #47
Moosdau wrote
(in article
<11*********************@g49g2000cwa.googlegroups. com>):
I think I've already known the answer.
the below is I copied from MSDN:
They should be ashamed.
The fflush function flushes a stream. If the file associated with
stream is open for output, fflush writes to that file the contents of
the buffer associated with the stream.
If the stream is open for input, fflush clears the contents of the
buffer.
Do they bother to point out that it is a non-standard extension
to have this behavior?

No?

Why not?

They want you to write non-portable code, it lends itself to
supporting their goal of monopoly.
#include <stdio.h>
#include <conio.h>

int main( void )
{
int integer;
char string[81];

/* Read each word as a string. */
printf( "Enter a sentence of four words with scanf: " );
for( integer = 0; integer < 4; integer++ )
{
scanf( "%s", string );
// Security caution!
// Beware allowing user to enter data directly into a buffer
// without checking for buffer overrun possiblity.
printf( "%s\n", string );
}

/* You must flush the input buffer before using gets. */
fflush( stdin ); // fflush on input stream is an extension to the
C standard
printf( "Enter the same sentence with gets: " );
gets( string );
printf( "%s\n", string );
}
This code is quite broken, for several reasons. Do you know
what they are?

The fact that MSDN includes bad code examples is hardly
surprising, considering the source (no pun intended).
then I know,I shouldn't use fflush(stdin) except in VC.
but in VC, it is safe.


Nothing about the above program is safe. Microsoft *claims*
that they are teaching their own programmers not to code this
way, yet it their examples still contain code which they are
*supposedly* not able to use themselves anymore. Think about
that before blinding following MSDN examples.
--
Randy Howard (2reply remove FOOBAR)
"The power of accurate observation is called cynicism by those
who have not got it." - George Bernard Shaw

Jan 3 '06 #48
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
Richard Heathfield wrote:
Chuck F. said:
Jordan Abel wrote:
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:

> No, it doesn't handle EOF. However, if you have flushln
> available you can write:
>
> #define flushstdin flushln(stdin)

I've never heard of flushln - what systems does it exist on?
> although I don't know why you would bother.

All you had to do was read this thread. I have published at
least two realizations of flushln in it.


Usenet is an asynchronous medium. Please don't assume that
everybody has been able to read all previous articles in a
thread. It is generally easy to skip around this problem; for
example, you could have said:

"However, if you use flushln() available on your system (source
for the fflushln function is provided upthread) you can
write..."

He's even more careless than that. One of the flushln
implementations was quoted in the article to which he replied, and
he snipped it! So there is no doubt he saw it.

Maybe he is one of the Wikipedia editors who are amusing you?


I didn't bother reading all the quoted text, and the text i did read
[and quote] said nothing to imply that it was a function you had written
in an earlier message - "if ___ is available on your system" implies (to
me) that it's a non-universally-available extension.
Jan 3 '06 #49
Jordan Abel wrote
(in article <sl**********************@random.yi.org>):
On 2006-01-03, Chuck F. <cb********@yahoo.com> wrote:
No, it doesn't handle EOF. However, if you have flushln available
you can write:

#define flushstdin flushln(stdin)


I've never heard of flushln - what systems does it exist on?


Source for it (looks pretty portable to me) was just posted
upthread. As such, it should be able to exist anywhere you want
it to, simply by using it.
--
Randy Howard (2reply remove FOOBAR)
"The power of accurate observation is called cynicism by those
who have not got it." - George Bernard Shaw

Jan 3 '06 #50

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

Similar topics

2
by: CR | last post by:
having a problem with the final strcpy of filename from *argv into a structure containing an array with 20 elements called fname It seems that strcpy & strncpy aren't stopping after null is found...
39
by: Teh Charleh | last post by:
OK I have 2 similar programmes, why does the first one work and the second does not? Basically the problem is that the program seems to ignore the gets call if it comes after a scanf call. Please...
57
by: Eric Boutin | last post by:
Hi ! I was wondering how to quickly and safely use a safe scanf( ) or gets function... I mean.. if I do : char a; scanf("%s", a); and the user input a 257 char string.. that creates a...
12
by: B Thomas | last post by:
Hi, I was reading O'Reilly's "Practical C programming" book and it warns against the use of scanf, suggesting to avoid using it completely . Instead it recomends to use using fgets and sscanf....
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...
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...
6
by: obdict | last post by:
Hello, I used scanf() in a while loop, which ensures that user input is valid (must be an integer no greater than 21 or less than 3). If user enters a number out of the range, or enters...
8
by: Neil | last post by:
Hello Just to let you know this not homework, I'm learning the language of C on my own time.. I recently tried to create a escape for user saying printf ("Do you want to continue? (y or n)");...
26
by: tesh.uk | last post by:
Hi Gurus, I have written the following code with the help of Ivor Horton's Beginning C : // Structures, Arrays of Structures. #include "stdafx.h" #include "stdio.h" #define MY_ARRAY 15
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
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,...

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.