RobertRDev
RobertRDev

Reputation: 35

Using width specifier with printf with no variable

I am working on a project for my C Programming Class. I know that when specifying width in a printf statement WITH a variable, it would look like this:

printf("%03d\n", tvQuantity);

With 3 being the width and 0 stating we want the number preceded by 0's.

My question is, how would I define a width in a printf statement where I'm not calling a variable? For example, to add a width of 6 to the following statement:

printf("Text here");

As there is no format specifier (such as %d), where would I place my width and other formatting arguments?

Upvotes: 1

Views: 2662

Answers (1)

Schwern
Schwern

Reputation: 164779

printf("Text here"); needs no width. It'll just print Text here.

You could write it as printf("%6s", "Text here") but that will do nothing as the width is a minimum and the text is longer than 6 characters.

If you want to pad the text, say with a width of 20, you can write printf("%20s\n", "Text here"). This could be useful if the string was defined in a constant.

To format your text in columns, you'd use multiple %s formats in a single printf.

printf("%20s %20s %20s\n", "Cell 1", "Cell 2", "Cell 3");

Upvotes: 2

Related Questions