infinite loop with scanf

M

Michael Goerz

Hi,

why does the following result in an infinite loop when the user does
*not* enter a number?

do{
printf("Enter Number: ");
} while ( ! scanf("%i", &input) );


Thanks,
Michael Goerz
 
J

Jack Klein

Hi,

why does the following result in an infinite loop when the user does
*not* enter a number?

do{
printf("Enter Number: ");
} while ( ! scanf("%i", &input) );


Thanks,
Michael Goerz

This is a very frequently asked question by beginning C programmers,
and as such it is in the FAQ for this group.

See http://c-faq.com/stdio/scanfjam.html

And you will very probably find a lot of useful information in the
rest of the FAQ as well. The link to its main page is in my signature
block.

Hint, always check to see if a newsgroup has a FAQ, and check for an
answer to your question if it does, before posting a question to a
group.
 
F

Fred Kleinschmidt

Michael Goerz said:
Hi,

why does the following result in an infinite loop when the user does
*not* enter a number?

do{
printf("Enter Number: ");
} while ( ! scanf("%i", &input) );


Thanks,
Michael Goerz

Think about where the file pointer will be after the scanf call
when a non-integer is entered.
 
C

CBFalconer

Michael said:
why does the following result in an infinite loop when the user
does *not* enter a number?

do{
printf("Enter Number: ");
} while ( ! scanf("%i", &input) );

Because nothing flushes the input data that does not form a
number. If something beginning with 'z', for example, does not
form a number, it still doesn't form a number on rescan.

Don't use scanf for interactive input. It bites.
 
R

Richard Heathfield

Fred Kleinschmidt said:

Think about where the file pointer will be after the scanf call
when a non-integer is entered.

Right where it was, of course, but I think you mean the file position
indicator.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top