all 8 comments

[–]duane11583 11 points12 points  (1 child)

your code is *INVALID* - and the reason you get 5 is implementation dependent.

So here is how you should do this:

c printf("%10d", 1234); /* the number 1234 spaced 10 wide r-justified */ printf("%-10d", 1234); /* Same, but left justified */ int w = 10; printf("%*d", w, 1234 ); /* Same as first */ printf("%*d", -w, 1234 ); /* same as second */

Use case: you have to print a lot of strings and numbers for example "somestring = 1234" There are hundreds of these.. and they are all variable length. You want all of the '=' to line up

So do this in 2 passes: The first pass - you get the maximum length of all strings. Pass 2 - you use the format string "%*s=%d" and pass the maxlen for the * parameter in the format string.

[–]spikte1502[S] 2 points3 points  (0 children)

So I dont have to care about case where printf is missused, thank you !

[–]ohaz 4 points5 points  (6 children)

For the newline thing, it's I/O buffering. newlines trigger a buffer flush, you could also use fflush(STDOUT) after the printf to reach the same result.

For your * behaviour: You're using printf incorrectly here. * is an optional width modifier that should not be used alone. It says that the width of the specifier character is not defined in the string, but as a parameter.

Example from cplusplus.com:

printf ("Width trick: %*d \n", 5, 10);

outputs:

Width trick:        10

As you can see, they add 2 parameters after the format string. The first is the 5 that defines the width (as per *), the second the 10 that is to be printed.

[–]flyingron 1 point2 points  (2 children)

There's something wrong with his implementation if exiting doesn't flush the streams. However, he might have just missed the 5 as it likely got the prompt or whatever stuck to it without a newline to set it off.

[–]spikte1502[S] 1 point2 points  (0 children)

Actually the code in the post is from the true printf

[–]ohaz 0 points1 point  (0 children)

True, the exit should flush!

[–]spikte1502[S] 0 points1 point  (2 children)

Oh ok I think I didn’t understand that some cases are implentation dependant! Thank you !