c printf pretty print formattion
I am printing a series of lines.The length of the lines are different.Sometimes I have to add spaces at the end of the line to align the lines.And at the end of each line I add "\n" character.The problem is that the new line after "\n" seems to start after some spaces on the next line. It is strange. Any suggestions or comments are appreciated.
switch(struct.var1) {
case 0:
switch(struct.var2)
{
case 1: printf("xyx");break;
case 2: printf("abc");break;
开发者_开发技巧}
break;
case 2: printf("xyz");break;
case 3: printf("xyz");break;
.
.
.
.
.
.
.
.
.
.
.
.
.
.
case n: printf("XYZ ");break;
case m:printf("ABC ");break;
case 0xff:
switch(struct.var2)
{
case 1: printf("MNO ");
case 2: printf("QRS ");
}
}//end of switch case.
printf("\n");
Please find the code snippet above. It is clearly an alignment problem with printf.I can't really spot any problem with the code.
The code you've posted isn't really sufficient to diagnose the problem, but my advice would be to sidestep it. Instead of printing spaces after your string to do the alignment, specify a field of the right width for your string.
The other point I'd make would be to use an array instead of a switch statement, if you can:
char *strings[256][2] = {
{"xyz", "abc"},
// ...
{"MNO", "QRS"}
};
// print selected string left justified in a 7-character wide field.
printf("%-7s\n", strings[struct.var1][struct.var2]);
It's not clear from the code you've posted whether the values involved in selecting the strings are entirely contiguous though. If they're not quite contiguous, but still fairly dense (I.e., you're using most but not quite all values), it may be easiest to just fill in the unused spots with empty strings and still use an array.
Are you on Windows? You might need to add a \r
to the end of your strings as well as the \n
.
精彩评论