-1

Can someone explain what does %-25s and %-90s do in the following code:

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
    printf ("%-25s %-90s","hello" ,"world");
}
Mat
  • 202,337
  • 40
  • 393
  • 406
proglove
  • 15
  • 5
  • 1
    Please avoid `using namespace std;`, it's bad practice. See https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – cigien Apr 04 '21 at 19:37
  • Actually, using it within header files is really bad, since it will be propagated to any dependent files - but within a source file after all includes there I do not see an issue with 'using namespace std;' IMHO - but personally I like the explicit way – Chilippso Apr 04 '21 at 19:44

3 Answers3

1

From the reference for std::printf, the - specifier after % is an optional flag that left-justifies the string to be printed:

-: the result of the conversion is left-justified within the field (by default it is right-justified)

So your program will write out "hello" followed by 20 whitespace characters, and then "world" followed by 85 whitespace characters.

cigien
  • 57,834
  • 11
  • 73
  • 112
1

-25 means left justify text in 25 blocks (character spaces). and %-90 means same just in 90 blocks. So for this:

printf ("|%-25s|%-15%|","hello", "world");

output would be:

|Hello                    |world          |
//          ^ 20 spaces             ^ 10 spaces

or this

printf ("|%-25s|%-15%|","hello", "world!!!");

outputs this:

|Hello                    |world!!!       |
//          ^ 20 spaces              ^ 7 spaces

If you omit -

printf ("|%25s|%15%|","hello", "world!!!");

you would get this:

|                    Hello|       world!!!|
//          ^ 20 spaces       ^ 7 spaces

I hope this helps, printing 90 spaces would be ridiculous.

@cigien beat me but go to c++ reference page.

https://en.cppreference.com/w/cpp/io/c/fprintf

0

%-25s

Left-justify (-) a null-terminated string (s) parameter (%) with 25 (25) elements length/padding (hello)

%-90s

Left-justify (-) a null-terminated string (s) parameter (%) with 90 (90) elements length/padding (world)

For more information you may see also: https://www.cplusplus.com/reference/cstdio/printf/

Chilippso
  • 451
  • 2
  • 9