如何使用sscanf()中的宏定义的可变宽度说明符 [英] How can I use variable width specifiers defined by a macro in sscanf()

查看:63
本文介绍了如何使用sscanf()中的宏定义的可变宽度说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图基于一个#define指定sscanf()调用中变量的宽度,该#define根据另一个#define计算其值.

I am trying to specify the width of variables in a sscanf() call based on a #define that calculates its values based on another #define.

当TEST定义只是一个数字时,它可以工作,但是当它成为计算时,代码将失败.让TEST调用另一个包含该计算的函数也不起作用.

It works when the TEST define is just a single number, but when it becomes a calculation, the code fails. Have TEST call another function that contains the calculation does not work either.

我正在使用的代码:

#include <stdio.h>

#define A       3
#define TEST    FUN()
#define FUN()   (A + 2)
#define STR(X)  _STR(X)
#define _STR(x) #x

int main()
{
    char input[] = "Test123";
    char output[10];

    sscanf(input, "%" STR(TEST) "s\n", output);

    printf("%s\n", output);

    return 0;
}

我在这里想念什么?

推荐答案

只需在执行过程中构建 scanf 格式字符串即可.例如:

Just build the scanf format string during execution. For example:

const int width_modifier = FUN();
char fmt[100] = {0};
snprintf(fmt, sizeof(fmt), "%%%ds\n", width_modifier);
sscanf(input, fmt, output);

我在这里想念什么?

What am I missing here?

预处理器进行文本替换,不计算内容.因此,%" STR(TEST)"s \ n" 扩展为包含%""3 + 2""s \ n" 的字符串,%3 + 2s" ,它是无效的 scanf 格式字符串.

Preprocessor does text replacement, it doesn't calculate things. So "%" STR(TEST) "s\n" expands to a string containing "%" "3 + 2" "s\n", which after concatenation is "%3 + 2s", which is an invalid scanf format string.

或者,您可以使用其他程序来准备要编译的源文件.一种流行的用途是在编译之前对文件进行预处理并能够计算算术的预处理器.流行的选择是 m4 :

Alternatively you can use other program to prepare the source file for compilation. A popular use is a preprocessor that preprocesses the file before compilation and that is able to calculate arithmetic. A popular choice is m4:

m4_define(`A', 3)
m4_define(`FUN', `eval(A + 2)')

#include <stdio.h>
#define STR(X)  #X
int main() {
    printf("%s", STR(FUN()));
}

m4 预处理并编译后将输出 5 .

preprocessed with m4 and compiled would output 5.

这篇关于如何使用sscanf()中的宏定义的可变宽度说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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