Dynamic width and precision in printf
Related Blog Items
- The Structure and Interpretation of Computer Programs
- Data structures lectures
- C++ Basics Tutorial - Lesson 10
- Operating Systems and Systems Programming
- Can we use printf() in an ISR?
Consider this statement:
printf("String: %9.8s", str);
Have you ever used printf in the form show above? Do you know how the printf formats this? If no, then read on…
In %9.8s above, 9 specifies minimum width and 8 specifies the precision. Instead of giving absolute numbers, you can use an asterisk, *.
The field width may also be specified by an asterisk, *, in which case an argument of type int is consumed and specifies the minimum width field. The result of specifying a negative width is undefined.
The precision may also be specified by an asterisk following the period, in which case an argument of type int is consumed and specifies the precision. If both the fields width and precision are specified with asterisks, then the field width argument precedes the precision argument.
For example:
#include <stdio.h>
#include <string.h>/* You calculate this according to your requirement */
#define SOME_VALUE 5int
main ( void )
{
char calvin[] = "Calvin and Hobbes";
char animal[] = "Animal Crackers";int width = strlen ( calvin ) + SOME_VALUE;
int prec = strlen ( calvin ) + SOME_VALUE;printf ( "%*.*s\n", width, prec, calvin );
return 0;
}
Popularity: 4%
You need to log on to convert this article into PDF
Related Blog Items - The Structure and Interpretation of Computer Programs
- Data structures lectures
- C++ Basics Tutorial - Lesson 10
- Operating Systems and Systems Programming
- Can we use printf() in an ISR?
Related Blog Items
- The Structure and Interpretation of Computer Programs
- Data structures lectures
- C++ Basics Tutorial - Lesson 10
- Operating Systems and Systems Programming
- Can we use printf() in an ISR?
No Comments
No comments yet.