C macro inside string in sprintf

北城以北 提交于 2020-01-04 02:49:07

问题


I use macro for formatted string copy. Example is given below. Code given bellow tries to pad null characters in remaining portion of string.

#include <stdio.h>

#define LEN     10
#define str(x)  #x

void main() {
    char a[LEN];
    int b = 3445;

    sprintf(a, "%-"str(LEN)"d", b);     // I want "%-10d" here
    printf("|%s|", a);
}

when I compile it with gcc -Wall prog.c it gives following warnings.

warning: format ‘%LE’ expects argument of type ‘long double’, but argument 3 has type ‘int’ [-Wformat]

This means that macro is not substituted properly. Can anybody help me here what is wrong here.


回答1:


You'd have to evaluate the argument to str once more to see the 10 inside the string

#define LEN     10
#define str_(x)  #x
#define str(x)  str_(x)

the way you did it, the argument to str is stringyfied directly, thus the LEN arrived in the format.



来源:https://stackoverflow.com/questions/17512658/c-macro-inside-string-in-sprintf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!