12

In c++, setw function is used to set the number of characters to be used as the field width for the next insertion operation. Is there any function in C, I mean, in standard c library, which does the same thing?

MD Sayem Ahmed
  • 27,838
  • 25
  • 109
  • 176
  • 1
    This may be the first time I've seen someone who understands how to use iostream formatters and not how to do the equivalent thing with `printf`... it's nearly always the other way around. :) – Tyler McHenry Jul 06 '10 at 17:01
  • 1
    Yeah, I run into the same things all the time. I learned the c++ style iostream formatters in college, but we use c-style at work. – Joe Lyga Apr 25 '13 at 17:03

4 Answers4

22

printf ("%5d", 42);

Will print 42 using 5 spaces. Read the man pages of printf to understand how character padding, overflow and other nuances work.

EDIT: Some examples -

int x = 4000;
printf ("1234567890\n");
printf ("%05d\n", x);
printf ("%d\n", x);
printf ("%5d\n", x);
printf ("%2d\n", x);

Gives the output

1234567890
04000
4000
 4000
4000

Notice that the %2d was too small to handle the number passed to it, yet still printed the entire value.

ezpz
  • 11,449
  • 6
  • 36
  • 38
  • 5
    Note that placing a `-` in front of the padding number will cause the output to align to the left. For example, `printf("%-7s, "12345");` will print `12345__` where the `_` is a space. This is opposed to `printf("%7s, "12345");` which will give you `__12345`. [Related Answer](http://stackoverflow.com/a/276869/1214700) – user12893298320392 Mar 07 '15 at 19:11
  • Thanks! @user12893298320392 – Sekomer Jun 07 '21 at 10:50
5

No, since the stream used in C doesn't maintain state the way the stream object does.

You need to specify with e.g. printf() using a suitable formatting code.

unwind
  • 378,987
  • 63
  • 458
  • 590
3

Another option is to define the format string as a variable:

char print_format[] = "%5d"; printf(print_format, 42);

The above is similar to C++ setw, in that you can set the contents of the variable before printing. Many occasions require dynamic formatting of the output. This is one method to achieve it.

Thomas Matthews
  • 54,980
  • 14
  • 94
  • 148
-2

setw Manipulator: This manipulator sets the minimum field width on output. The syntax is: setw(x) Here setw causes the number or string that follows it to be printed within a field of x characters wide and x is the argument set in setw manipulator. The header file that must be included while using setw manipulator is Sample Code

 #include <iostream>
 using namespace std;
 #include <iomanip> 
  
 void main( )
 {
 int x1=12345,x2= 23456, x3=7892;
 cout << setw(8) << "Exforsys" << setw(20) << "Values" << endl
         << setw(8) << "E1234567" << setw(20)<< x1 << endl
         << setw(8) << "S1234567" << setw(20)<< x2 << endl
         << setw(8) << "A1234567" << setw(20)<< x3 << endl;
 } 
NAND
  • 655
  • 8
  • 22