473,837 Members | 1,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,&do r))
{
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
51 3943
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*****@invali d.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(buffe r, "%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.c om, 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********@yah oo.com> wrote in message
news:R7******** ************@ma ineline.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********@yah oo.com> wrote in message
news:R7******** ************@ma ineline.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_Keit h) 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.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
"pemo" <us***********@ gmail.com> writes:
"Chuck F. " <cb********@yah oo.com> wrote in message
news:R7******** ************@ma ineline.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 :
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 #20

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

Similar topics

2
1632
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 but appending other trash overwriting the array possibly? Any help would be appreciated! (if you need all the code let me know) int main(int argc, char *argv) { int *arg_chk; int i; int j=0;
39
100822
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 anything even a hint would be really helpful, I cant for the life of me see why the 2nd prog wont work... gets before scanf code:---------------------------------------------------------------------
57
11795
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 problem.. same for gets.. even if you create a char array that's 99999999999999 char long.. if the user input something longer it will still be a bug.. and I don't want
12
9879
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. However no explanation is offered other than that scanf handels end of lines very badly. I have exeperienced such problems when doing some numerical programming but never understood it. Things like some consequitive scanfs would not read in values...
7
7674
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 scanf cannot fill any fields it returns EOF. I have run some tests on scanf and, so far, I've not found an EOF return. For example: If the programer formats scanf for an int or
33
3182
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 help me in finding why such thing is happening and what the remedy to it is. Kindly bear with my English. int main ()
6
26307
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 non-number, he/she will be asked to retry. /* start */ int n;
8
2382
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)"); The scanf statement follows the prompt(printf above) which is the last statement in the while loop, before the "}"
26
4546
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
9840
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
9682
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
10565
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
10623
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
10270
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
5847
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
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
2
4040
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3124
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.