Why call sscanf() with argv[] can only use once?

2019-03-04 05:31发布

问题:

I need to get argv[1] and argv[2] to different types. I found that I could only use sscanf() once or the next string in argv cannot be retrieved. Here's my code.

int main( int argc, char *argv[])
{
    char t;
    float temp;
    sscanf(argv[1], "-%[cf]",&t);
    sscanf(argv[2], "%f", &temp);
    return 0;
}

Only the first sscanf() can get the formatted value. How could I also get done with argv[2]?

回答1:

Attempt to save string data in a char leading to undefined behavior (UB).

"%[]" expects to match a character array.

// char t;
// sscanf(argv[1], "-%[cf]",&t);

char t[100];
if (sscanf(argv[1], "-%99[cf]",t) != 1) Handle_Failure();

Recommend:
Add the width limit, like 99, to limit string input. Set to 1 less than the size of t.
Check the return value of sscanf().



标签: c argv scanf