为什么用 argv[] 调用 sscanf() 只能使用一次? [英] Why call sscanf() with argv[] can only use once?

查看:29
本文介绍了为什么用 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().

这篇关于为什么用 argv[] 调用 sscanf() 只能使用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆