4

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?

1

1 Answer 1

11

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/

1
  • I didn't know you could do that! Thanks.
    – Einheri
    Commented Feb 1, 2015 at 15:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.