2013-07-07 39 views
3

我使用宏進行格式化的字符串複製。示例如下。下面給出的代碼嘗試在字符串的剩餘部分填充空字符。sprintf中的C宏內部字符串

#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); 
} 

當我編譯它與gcc -Wall prog.c它給出以下警告。

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

這意味着,宏觀未正確取代。任何人都可以在這裏幫我解決這裏有什麼問題。

+0

這將填充空白空間。我們可以填充'\ 0',而不是空格 – Ravi

回答

6

你不得不論證評估,以str一次看到10串

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

你所採取的方式,將參數str直接stringyfied,因此LEN抵達內格式。

+0

真正的作品.... – Ravi