Search code examples
cscanfc-stringsconversion-specifier

sscanf check doesn't work when given more input than required


I have an if statement that is supposed to check if the user entered exactly 4 arguments separated by a var like the following: param1,param2,param3,param4 . Problem is that it doesn't return an error if the user gives more than 4 inputs. It only returns an error when he gives less than 4.

char input[60];
char a1[42], a2[42], a3[42], a4[1];
printf("Enter info");
fgets(input, 60, stdin);
if (4 != sscanf(input,"%1[^,\n], %1[^,\n], %1[^,\n], %[^,\n]",a1, a2, a3, a4)) {
    return printf("Error"),1;
}
else
{
    printf("In");
}

I can't seem to find why. Thanks for your help


Solution

  • If sscanf reads data successfully it will return the number of filled variables. If you want fewer than 4 variables to be filled, to be considered successful you should say:

    if (sscanf(input,"%1[^,\n], %1[^,\n], %1[^,\n], %[^,\n]",a1, a2, a3, a4)<=4) {
            printf("In");
    }
    

    Also, in failure sscanf will return EOF, but it won't return a number larger than 4.

    (Note that for a4[1] you don't have space for terminator. Use at least a4[2].)

    and since you want more than 4 variable filled to be considered as a failure you can add one variable to sscanf if it's filled ,it means more than 4 input was taken which is wrong and you will print error

    edit: if you exactly want 4 variable, use below code:

        char input[60];
        char a1[42], a2[42], a3[42], a4[2],a5[42];
        printf("Enter info");
        fgets(input, 60, stdin);
        if (sscanf(input, "%1[^,\n], %1[^,\n], %1[^,\n], %1[^,\n], %[^,\n]", a1, a2, a3, a4,a5) == 4) {
            printf("In");
        }
        else
        {
            printf("error");
            exit(EXIT_FAILURE);
        }
    }
    

    now if you give a,b,c,d,e you will print error , because now more than 4 variables are filled.