简体   繁体   中英

How to use macros in printf function

So I have this macro and a bunch others defined in my header file

#define COL1WIDTH 16

Which I want to use to print something like this:

word  25 Dir1/FileB 129 Sat Jan 1 00:00:02 2011 12 1(x4), 2(x2), 3(x2), 4(x2), 5(x2) 

How does the syntax to get the macro work? Tried a bunch and it keeps screwing up.

Tried this

printf("%COL1WIDTHs\t",index->terms[0].term);

printf("%" #COL1WIDTH "s\\t", ...

在C预处理器中阅读令牌粘贴和字符串化的信息。

Macros aren't expanded inside strings. Here there's a decent workaround — write

printf("%*s\t", COL1WIDTH, index -> terms[0].term);

and COL1WIDTH will be used in place of the * .

Modify your code as below and it will serve the purpose

#define COL1WIDTH "16"    //define the constant in double quotes

printf("%"COL1WIDTH"s\t",index->terms[0].term); //place macro out of quotes so it can expand            
                                                //during the precompilation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM