Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

06
Feb

Dynamic width and precision in printf

Related Blog Items

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 5

int
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

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image