HOWTO: Use #define Constants in printf() Format StringsLast reviewed: October 3, 1997Article ID: Q117429 |
The information in this article applies to:
SUMMARYUsing #define constants to specify precision or width directly within the printf() format string does not work as expected. The constant identifier is printed literally. For example, at times, it is convenient to define a maximum output precision or width for printing or scanning values within a given program. The following printf() statement truncates the output string at 20 characters:
printf( "This is the string: %.20s\n",szBuf );However, the following statement:
#define MAXSIZE 20 printf( "This is the string: %.MAXSIZEs\n",szBuf );prints the message "This is the string: MAXSIZEs".
MORE INFORMATIONA couple of steps are needed to get the behavior you want:
#define MAXSIZE 20 #define STRX(y) #y // "Stringizes" parameter y. #define STR(x) STRX(x) // Evaluates x printf( "This is the string: %."STR(MAXSIZE)"s\n", szBuf );First, the constant is evaluated so that it does not come through as the literal constant identifier name ("MAXSIZE"). Then, the STR macro causes MAXSIZE to be evaluated. Finally, the STRX macro uses the # operator to cause the value to be placed in double quotes and concatenated to the format string.
MORE INFORMATIONBelow is a simple program that includes the code described above.
Sample Code
/* Compile option needed: none */ #include <stdio.h> #define MAXSIZE 20 #define STRX(y) #y // "Stringizes" parameter y. #define STR(x) STRX(x) // Evaluates x void main( void ) { char szBuf[17] = { "Howdy, stranger!" }; printf( "This is the string: %.20s\n",szBuf ); printf( "This is the string: %.MAXSIZEs\n",szBuf ); printf( "This is the string: %."STR(MAXSIZE)"s\n", szBuf ); } Keywords : CRTIss Version : MS-DOS:7.0;WIN3X:1.0,1.5;WINNT:1.0,2.0,2.1,4.0,5.0; Platform : MS-DOS NT WINDOWS Issue type : kbhowto |
================================================================================
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |