Hello!

I have a small doubt about formal specifiers.
I have seen in many programs of printf statements,writing "%2d".What is the use of writing
an integer before d or any formal specifiers.

Thanks in advance

Recommended Answers

All 3 Replies

Read about the format specifiers! The 2 in %2d says to display the integer in 2 or more characters. For example if x = 1, then it will show a space before the 1, like in " 1". But if x = 123 then it will just show all the difits, such as "123".

If you want the number left-justified in the field then use "%-2d". In that case it will display "1 ", with the space on the right instead of the left.

If you want 0 filled to the left, then use "%02d", and when x = 1 it will display it as "01" instead of " 1".

>What is the use of writing an integer before d or any formal specifiers.
It gives you more control over the output than the defaults. You can override field width, padding, justification, precision, sign display, and whatnot. In this case, you're changing the field width. For example, if you're writing a fixed width report where a field has N columns assigned to it, you can say fprintf(out, "%*d", N, value); to print the value right justified with whitespace padding that fits the the fixed column[1]. This is as opposed to the alternative where you would need a solution like this:

size_t value_len = get_value_len(value);

/* Pad unused field area with whitespace */
for (i = 0; i < N - value_len; i++)
    putc(' ', out);

fprintf(out, "%d", value);

A more common example might be pretty printing a matrix of integers:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i, j;

    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++)
            printf("%4d", rand() % 100);
        puts("");
    }

    return 0;
}

Note that the last value on each row does not end with a space (which would happen if you used "%d " as the format string), and the columns are lined up nicely despite values of varying width.


[1] Of course, the default behavior is that if the value is larger than the field width, it's not truncated, so in the case of a fixed width report you might have issues. But you get the idea.

Adding to what has already been written, if you're looking for a more formal piece of information, I suggest you should check here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.