The following test code produces an undesired output, even though I used a width parameter:
int main(int , char* []) { float test = 1234.5f; float test2 = 14.5f; printf("ABC %5.1f DEF\n", test); printf("ABC %5.1f DEF\n", test2); return 0; }
Output
ABC 1234.5 DEF ABC 14.5 DEF
How to achieve an output like this, which format string to use?
ABC 1234.5 DEF ABC 14.5 DEF
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following. char *ptr = "Hello"; printf("%40s\n", ptr); That will give you 35 spaces, then the word "Hello".
As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.
%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].
%g. It is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the value after the decimal in input would be exactly the same as the value in the output.
The following should line everything up correctly:
printf("ABC %6.1f DEF\n", test); printf("ABC %6.1f DEF\n", test2);
When I run this, I get:
ABC 1234.5 DEF ABC 14.5 DEF
The issue is that, in %5.1f
, the 5
is the number of characters allocated for the entire number, and 1234.5
takes more than five characters. This results in misalignment with 14.5
, which does fit in five characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With