Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-equivalent of the 'setw' function

Tags:

c

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?

like image 251
MD Sayem Ahmed Avatar asked Jul 06 '10 14:07

MD Sayem Ahmed


3 Answers

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.

like image 178
ezpz Avatar answered Oct 21 '22 05:10

ezpz


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.

like image 5
unwind Avatar answered Oct 21 '22 06:10

unwind


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.

like image 3
Thomas Matthews Avatar answered Oct 21 '22 05:10

Thomas Matthews