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);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ElQwerto
  • 11
  • 4

1 Answers1

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

Community
  • 1
  • 1
  • 1
    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. – Jonathan Leffler Mar 25 '17 at 23:52