Home > Mobile >  Multiple conditions with scanf in C
Multiple conditions with scanf in C

Time:11-21

TLDR: I need to check if the input I am scanning with scanf into an array is really an integer while using EOF.

I need to scan numbers into an array until EOF. I am doing everything with statically allocated memory, since I am quite a beginner and for now dynamically allocated memory is hard for me to understand. I am also using getc to get the "\n" input at the end (but this is not a problem - just saying this so you know). My first thought how to do it is:

while(scanf("%d", &number[i][j]) != EOF )
**some code**

But this solution doesn't check if the input is integer. For example if my input is.

1 2 3
4 0 5
2 3 a

the code doesn't stop, since the value of the last array is 0 until i scan a number into it. My solution to that is

while(1)
    if(scanf("%d", &number[i][j]) != 1)
        printf("Incorrect input.\n");
return 0;

but since the EOF is equal to -1, that means I am getting input even at the end of the file which I don't want. So is there any way to have more conditions comparing the scanf? For example (I know this doesn't work, but to help you understand what I mean):

while(1)
    if(scanf("%d", &number[i,j] != 1 && scanf("%d", &number[i,j]) != EOF)
        printf("Incorrect input.\n");
return 0;

but this "solution" takes the input twice. I also found some answers on this site suggesting to use other way of taking input instead of scanf but I need to specifically use the scanf function.

CodePudding user response:

You can save the return value of scanf into a variable of type int and then perform further tests on it later:

int val, ret;

while ( ( ret = scanf( "%d", &val ) ) != EOF )
{
    if ( ret != 1 )
    {
        printf( "Incorrect input.\n" );
        exit( EXIT_FAILURE );
    }

    //input is ok, so do something with the input value
    DoSomethingWithValue( val );
}

//if this line of code is reached, then EOF has been encountered
  • Related