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

假如想象 提交于 2019-12-04 06:04:13

问题


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().



来源:https://stackoverflow.com/questions/33179316/why-call-sscanf-with-argv-can-only-use-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!