为什么用 argv[] 调用 sscanf() 只能使用一次?

问题描述:

我需要将 argv[1] 和 argv[2] 设置为不同的类型.我发现我只能使用 sscanf() 一次,否则无法检索 argv 中的下一个字符串.这是我的代码.

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;
}

只有第一个 sscanf() 才能得到格式化的值.我如何才能完成 argv[2]?

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

尝试将字符串数据保存在 char 中会导致未定义行为 (UB).

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

推荐:
添加宽度限制,如 99,以限制字符串输入.设置为小于 t 的大小 1.
检查sscanf()的返回值.

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