Column alignment in pin C

I am trying to write a program that displays the numerical value of certain character constants (those contained in if ). The code works except for one problem. It is assumed that the output should be well-aligned in columns, but as shown below, this is not the case. What is the best way to align columns properly?

Here is my code:

 #include <stdio.h> #include <ctype.h> int main() { unsigned char c; printf("%3s %9s %12s %12s\n", "Char", "Constant", "Description", "Value"); for(c=0; c<= 127; ++c){ if (c == '\n') { printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\n","newline","0x", c); }else if (c == '\t'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\t","horizontal tab","0x", c); }else if (c == '\v'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\v","vertical tab","0x", c); }else if (c == '\b'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\b","backspace","0x", c); }else if (c == '\r'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\r","carriage return","0x", c); }else if (c == '\f'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\f","form feed","0x", c); }else if (c == '\\'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\","backslash","0x", c); }else if (c == '\''){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\'","single quote","0x", c); }else if (c == '\"'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\"","double quote","0x", c); }else if (c == '\0'){ printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\0","null","0x", c); } } return 0; } 

Here's the conclusion:

Output

+5
source share
1 answer

Using \t leaves you in the grip of your output device. Instead, you can use the minimum field width for strings, for example. %-20s will print at least 20 characters, on the right - a space with spaces.

%-20.20s will trim the string if it was longer; %-20s will hit everything else on the right. - means "left justify" (by default this is an excuse)


To avoid code duplication, you can use a helper function, for example:

 void print_item(char code, char const *abbrev, char const *description) { printf("%3d %7s %20.20s %#03x\n", code, abbrev, description, (unsigned char)code); } // ... in your function if (c == '\n') print_item(c, "\\n", "newline"); 

I changed the printf format line:

  • Using %20.20s as above
  • %#03x , # means it will add 0x for you
  • (unsigned char)code for the latter means that it will behave well if you pass any negative characters. (Typically, the range of characters varies from -128 to 127).
+4
source

Source: https://habr.com/ru/post/1242744/


All Articles