How to format strings using printf() to get equal length in the output?

后端 未结 6 1623
一个人的身影
一个人的身影 2020-11-28 05:10

I have two functions, one which produces messages like Starting initialization... and another which checks return codes and outputs \"Ok\", \

相关标签:
6条回答
  • 2020-11-28 05:50

    There's also the rather low-tech solution of counting adding spaces by hand to make your messages line up. Nothing prevents you from including a few trailing spaces in your message strings.

    0 讨论(0)
  • 2020-11-28 05:52

    Additionally, if you want the flexibility of choosing the width, you can choose between one of the following two formats (with or without truncation):

    int width = 30;
    //no truncation uses %-*s
    printf( "%-*s %s\n", width, "Starting initialization...", "Ok." );
    // output is "Starting initialization...     Ok."
    
    //truncated to the specified width uses %-.*s
    printf( "%-.*s %s\n", width, "Starting initialization...", "Ok." ); 
    // output is "Starting initialization... Ok."
    
    0 讨论(0)
  • 2020-11-28 05:56

    You can specify width on string fields, e.g.

    printf("%-20s", "initialization...");
    

    and then whatever's printed with that field will be blank-padded to the width you indicate.

    The - left-justifies your text in that field.

    0 讨论(0)
  • 2020-11-28 06:00

    printf allows formatting with width specifiers. e.g.

    
    printf( "%-30s %s\n", "Starting initialization...", "Ok." );
    

    You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

    0 讨论(0)
  • 2020-11-28 06:00

    There's also the %n modifier which can help in certain circumstances. It returns the column on which the string was so far. Example: you want to write several rows that are within the width of the first row like a table.

    int width1, width2;
    int values[6][2];
    printf("|%s%n|%s%n|\n", header1, &width1, header2, &width2);
    
    for(i=0; i<6; i++)
       printf("|%*d|%*d|\n", width1, values[i][0], width2, values[i][1]);
    

    will print 2 columns of the same width of whatever length the two strings header1 and header2 may have. I don't know if all implementations have the %n but Solaris and Linux do.

    0 讨论(0)
  • 2020-11-28 06:00

    Start with the use of Tabs, the \t character modifier. It will advance to a fixed location (columns, terminal lingo). However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).

    To fix that, write your "OK/NOK" stuff using fixed number of Tabs (5? 6?, try it), then return (\r) without new-lining, and write your message.

    0 讨论(0)
提交回复
热议问题