Hi,

Kindly I hope that I can find help regarding reusing of scanf.

If the user should enter only integers not floats and the scanf is within a for loop. how can I force the program to continue normally when EOF happens as a result of wrong input?

Example:

int i , x, n=5;

            for(i=0;i<n;i++)
            {

                if ( (scanf ("%d", &x)==1) )
                    {

                        printf("Integar is entered\n"); 
                    }
                else
                    {
                        printf("Please enter an integer\n");
                        i--;
                    }
            }

the above program just goes into infinite loop, how can I let the program accepts continuous numbers as inputs without interrupting (i.e. let the user to input a correct input istead of the wrong one) ?

you need to remove the trailing new line so that it won't end up in an infinite loop try using getchar for this
here's an example

int i , x, n=5, ch;
            for(i=0;i<n;i++)
            {
                if ( (scanf ("%d", &x)==1) )
                    {
                        printf("Integar is entered\n"); 
                    }
                else
                    {
                        printf("Please enter an integer\n");
                        i--;
                    }
            //Clean up the stream (assumes everything left is garbage
               while ((ch = getchar()) != '\n' && ch != EOF)
                  {
                   // All work done in the condition
                  } 
            }

If the user should enter only integers not floats

I doubt the above code will work in detecting floats, for that you need to check for the enter key
here's an example

int number;
char enter;
printf("\nEnter number: ");
if(scanf("%d%c", &number, &enter) == 1 || enter != '\n'){ // enter is used to catch the enter key when pressed
    printf("you did not enter an integer number");   

}
else{
    printf("valid integer followed by enter key\n");    
}

though you can't use this inside a loop

First question, what does EOF have to do with this problem?

The solution has to do with being able to read non-digit characters without causing an error. Search for the thousands of responses to this error using "scanf integer character input"

This article has been dead for over six months. Start a new discussion instead.