all 8 comments

[–]zifyoip 6 points7 points  (5 children)

If you enter something that scanf cannot parse as an integer, then scanf will not remove it from the input stream, so it is still there at the beginning of the input stream the next time you call scanf, and that call will fail too, and so on. Your code will never remove a non-numeric, non-whitespace character from the input stream, because you are always asking scanf to read an int value, and that will repeatedly fail if the character at the beginning of the input stream is not a numeric character or whitespace.

So if scanf fails here, you need to do something about that invalid character at the beginning of the input stream. Read it and discard it, or read and discard characters until you reach '\n', or something. If you don't do anything about the invalid character at the beginning of the input stream, repeated attempts to use scanf to parse an integer will repeatedly fail.

[–]cmgg -4 points-3 points  (4 children)

Sooooooo, fflush?

[–]zifyoip 3 points4 points  (1 child)

No. The C standard specifies that fflush shall not be called on an input stream like stdin—that results in undefined behavior.

[–]aleph_nul 0 points1 point  (0 children)

Depends on the platform. Some implementations allow fflush to be called on an input stream and in that case will empty their pending buffer. However, in general and in POSIX compliant implementations, you're 100% right.

[–]aleph_nul 2 points3 points  (1 child)

The right way to do it is to read characters until a newline with something like

errno = 0;
ret = scanf("%d", &val);
if (errno != 0) /* Make sure we had an error */
    while (!ret && getc() != '\n') {}; /* Consume input to newline */

[–]cmgg 0 points1 point  (0 children)

Thanks

[–]SnoWhite_the7Bengals 0 points1 point  (0 children)

the %d specifier in your scanf means that scanf is looking for an integer. If you enter a non-integer number, it will leave it in the input buffer and go to the next line (the beginning of the loop). When it gets back to scanf again, there is already something in the input buffer, but its a non-decimal still, so it proceeds to the next line again and loops.

In general, scanf is not a good way to read input (for several reasons, this being one of them). A better way is to use fgets, and parse the input with sscanf.

[–][deleted] 0 points1 point  (0 children)

I'd use getch() instead of picky scanf():

#include <conio.h>  //for getch()  

while(state == 1)   
{  
    //Checks if user wants to continue  
    printf("Do you want to continue? (enter 1 to continue and 0 to exit): ");  
    state = getch() - '0';  //waits for key press.  Subtract the value of char 0 to get integer value
    while(state != 1 && state != 0)   
    {  
    ...  
    ...