如何通过可变长度宽度说明在sscanf的? [英] How to pass variable length width specifier in sscanf?

查看:215
本文介绍了如何通过可变长度宽度说明在sscanf的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sscanf(input_str, "%5s", buf); //reads at max 5 characters from input_str to buf

但我需要使用类似%MACRO_SIZEs代替%5S

But I need to use something like %MACRO_SIZEs instead of %5s

一个平凡的解决方案是创建一个相同的格式字符串

A trivial solution is to create a format string for the same

char fmt_str[100] = "";    
snprintf(fmt_str, 100, "%%%ds", MACRO_SIZE);
sscanf(input_str, fmt_str, buf);

有没有更好的方法来达到同样的?

Is there a better way to achieve the same?

推荐答案

如果您MACRO_SIZE是常量在编译时,你可以试试这个:

if your MACRO_SIZE is const at compile time, you can try this:

#define MACRO_SIZE "5"
snprintf(fmt_str, 100, "%" MACRO_SIZE "s", buf);

这篇关于如何通过可变长度宽度说明在sscanf的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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