Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this possible with printf?

Tags:

c

printf

libc

I understand that, with an oversize string, you can print out the first few characters with:

printf(".5s\n",string);

and with an undersize string, you can pad it with space:

printf("% 5s\n",string);

Is there a way to achieve both of these at once? i.e. pad it with 0 or space if it's short, and truncate it if it's long?

like image 603
Einheri Avatar asked Dec 20 '22 07:12

Einheri


1 Answers

Yes, you can just combine it to this:

printf("%5.5s\n", string);

So if your string is 1, the output is:

    1
//^ 4 Spaces here

And if your string is 123456, the output is:

12345
   //^ 6 doesn't get displayed

Also for more information about printf() and as a reference see this link: http://www.cplusplus.com/reference/cstdio/printf/

like image 79
Rizier123 Avatar answered Dec 28 '22 07:12

Rizier123