scanf error handling C

前端 未结 2 1684
日久生厌
日久生厌 2021-01-03 10:50

Say If i want an input to be

[Name] [Name]

How would I detect

[Name] [Name] [Name] 

and return error?

2条回答
  •  萌比男神i
    2021-01-03 11:35

    scanf returns the number of validly converted arguments. So in your first case, the return value would be 2, in the latter case 3.

    To check the right amount of parameters, this might help:

    char in[20];
    char out[20];
    char error[20];
    int check;
    
    check = scanf(" %s %s %s", out, in, error);
    if(check != 2)
    {
        // TODO: error handling
    }
    

    EDIT: now it should be working, see comments below.

    Of course, as stated by other posters: scanf is not considered a quite safe function since buffer overflows can occur, and you should avoid using it. It is better to read the inputs to a buffer with fgets() and the try to parse the arguments you want.

提交回复
热议问题