1

I have a problem with getting this string to even out nicely into columns despite what size each of the strings are. I've tried different formatting and other stuff; it's just not working. The way the function works is that before the printCompanyTable works, there's another function that updates all the string variables you see below, so I'm guessing that's where the problem might be, I think.

int printCompanyInfo() { // this will print out the format for as long as I need it. char discount[30]; char tax[30]; if (discountTypeLookup == 0) { strcpy_s(discount, 30, "Not Applicable"); } else if (discountTypeLookup == 1) { strcpy_s(discount, 30, "before Tax"); } else if (discountTypeLookup == 2) { strcpy_s(discount, 30, "After Tax"); } else if (discountTypeLookup == 3) { strcpy_s(discount, 30, "Before Tax > 14,500"); } if (payTaxLookup == 0) { strcpy_s(tax, 30, "No"); } else if (payTaxLookup == 1) { strcpy_s(tax, 30, "Yes"); } printf_s("%s %s %f %s %s %s\n", companyId, companyNameLookup, discountRateLookup, discount, tax, pickUpBayLookup); return(0); } 
2
  • 1
    in your output you can set a width for the column and thus maintain evenly spaced columns - look here for reference stackoverflow.com/q/1809399/3858121 Commented Mar 25, 2017 at 22:30
  • There's an awful lot of global variables in use — that bodes ill. Commented Mar 25, 2017 at 23:27

1 Answer 1

1

In addition to the accepted answer in the link provided by Japu_D_Cret, if you use %-30s it will format the string to 30 chars but if the string is longer, it will print all of that...

Try with this:

printf_s("%s %s %f %-30.30s %-30.30s %s\n", companyId, companyNameLookup, discountRateLookup, discount, tax, pickUpBayLookup); 

Using the . means it will format the string to exactly 30 chars and the - means the string will be left justified (the default is right justified).

EDIT: Adjusted the code to reflect the correction made by @Jonathan Leffler

Sign up to request clarification or add additional context in comments.

1 Comment

Note that %-.30s means "left justify; truncate at 30 unless you're done sooner". If you want the field width to be 30 even if the string is shorter, you need to use %-30.30s. In the general case, you can use %-*.*s and provide the same int value for each * before the string — or, indeed, you can use different values for the two integers if you wish, but quite often you want the same value twice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.