简体   繁体   中英

What's wrong with my printf output?

having trouble debugging the reason i'm getting a space between oct-nov and nov-dec. here is the code:

if (month == 1)
printf("jan");

if (month == 2)
printf("feb");

 if (month == 3)
 printf("march");

if (month == 4)
printf("apr");

if (month == 5)
printf("may");

if (month == 6)
printf("jun");

if (month == 7)
printf("jul");

if (month == 8)
printf("aug");

if (month == 9)
printf("sept");

if (month == 10)
printf("oct");

if (month == 11)
printf("nov");

if (month == 12)
printf("dec");



printf(" %c       | %.1f | %.1f | %.1f | %.1f     |\n", month, monthly->maxTemperature,
monthly->minTemperature, monthly->averageTemperature, monthly->totalPrecipitation);

have tried changing the spacing as well but its always between those 2 months for some reason. Thanks!

edit:

it is part of this function :

void printMonthlyStatistic(int month,const struct MonthlyStatistic*   monthly)

and is called in main program like this:

 for(i=0;i<12;i++){
   printMonthlyStatistic(i+1,&monthly[i])

my sample output:

|   Month   | High  |  Low  |  Avg  | Precip  |
|-----------|-------|-------|-------|---------|
jan        | 9.8 | -26.2 | -7.8 | 55.3     |
feb        | 7.5 | -23.3 | -8.6 | 33.1     |
march        | 14.2 | -19.6 | -4.7 | 33.2     |
apr        | 23.7 | -5.3 | 6.2 | 56.8     |
may        | 33.0 | -0.6 | 13.9 | 62.7     |
jun        | 32.1 | 8.0 | 19.7 | 69.7     |
jul        | 34.9 | 12.6 | 22.2 | 181.8     |
aug       | 31.5 | 11.0 | 20.9 | 69.2     |
 sept          | 34.1 | 5.0 | 16.1 | 69.0     |
oct 
   | 24.8 | -2.9 | 10.8 | 56.9     |
nov 
       | 16.0 | -12.8 | 2.1 | 36.2     |
dec 
       | 15.6 | -17.8 | -4.2 | 65.8     |

%c prints a character with the specified charcode, and if you use ASCII code, 10 is newline and 11 is vertical tab.

Also, you should use an array instead of writing those too-many if s.

Try this:

static const char *month_names[] = {"jan", "feb", "march", "apr", "may", "jun", "jul", "aug", "sept", "oct", "nov", "dec"};
printf("%-11s| %.1f | %.1f | %.1f | %.1f     |\n",
  1 <= month && month <= 12 ? month_names[month - 1] : "", monthly->maxTemperature,
  monthly->minTemperature, monthly->averageTemperature, monthly->totalPrecipitation);

Your problem is the %c which prints a char. The ASCII value NewLine is 10 and the Vertical Tab is 11: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM