将预处理器标记转换为字符串
我正在寻找一种将预处理器标记转换为字符串的方法。
具体来说,我在某个地方得到了:
#define MAX_LEN 16
并且我想用它来防止缓冲区溢出:
char val[MAX_LEN+1]; // room for \0
sscanf(buf, "%"MAX_LEN"s", val);
我愿意接受其他方法来完成同样的事情,但仅限标准库。
I'm looking for a way to convert a preprocessor token to a string.
Specifically, I've somewhere got:
#define MAX_LEN 16
and I want to use it to prevent buffer overrun:
char val[MAX_LEN+1]; // room for \0
sscanf(buf, "%"MAX_LEN"s", val);
I'm open to other ways to accomplish the same thing, but standard library only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请参阅使用FILE和LINE 报告错误:
所以你的问题可以通过这样做来解决
sscanf(buf, "%" TOSTRING(MAX_LEN) "s", val);
。See Using FILE and LINE to Report Errors:
So your problem can be solved by doing
sscanf(buf, "%" TOSTRING(MAX_LEN) "s", val);
.我在网上找到了答案。 ( https://gcc.gnu.org/onlinedocs/gcc -3.4.3/cpp/Stringification.html)
I found an answer online. ( https://gcc.gnu.org/onlinedocs/gcc-3.4.3/cpp/Stringification.html )
这应该可行:如果不行,则需要“双重扩展”技巧:
This should work:If not, it'll need to "double expansion" trick:
您应该使用双扩展字符串化宏技巧。 或者只是拥有一个
并保持同步。 (这有点麻烦,但只要定义彼此相邻,您可能会记住。)
实际上,在这种特殊情况下,
strncpy
不就足够了吗?不过,如果是
printf
,这会更容易:You should use the double-expansion stringification macro trick. Or just have a
and keep it in sync. (That's a bit of a bother, but as long as the definitions are right next to each other, you'll probably remember.)
Actually, in this particular case, wouldn't
strncpy
suffice?If it were
printf
, though, this would be easier:虽然之前的一些答案“有效”,但我个人建议仅使用简单的字符串 API,而不是 libc。
有许多可移植的 API,其中一些还进行了优化,以便轻松包含在您的项目中......还有一些像 ustr 的空间开销很小,并且支持堆栈变量。
While some of the previous answers "work", personally I'd recommend just using a simple string API instead of the dreck that comes in libc.
There are a number of portable APIs, some of which are also optimized for ease of inclusion in your project ... and some like ustr have a tiny space overhead and support for stack variables.
在我的示例中,生成的格式为
%16s%16s%d
:输出
In my example, the format to generate is
%16s%16s%d
:Output