2

I am writing a code for a weather database, but when I go to print out the city and temperatures my first line is off by 1 character, and I cannot figure out why. One thing I did notice was that when i print for example printf("%20s", city); only the first city is being modified.

This is for a intro to C-Programming and they have not learned much about strings yet, which is why I read in character by character.

Here is the snippet of code I am referring to;

while(TRUE) {
  for(
    i=0; 
    fscanf(input,"%c", &c)!=EOF && c!='#';
    i++)
  {  //i.e. city#..
    city[i]=c;
  }

  if(c=='#') {
    city[i] = '\0';         //Next line scans in the weather for the days of the week
    fscanf(input, " (%f, %f), (%d, %d), (%d, %d), (%d, %d), (%d, %d), (%d, %d), (%d, %d), (%d, %d)",&h_avg, &l_avg,&s1,&s2,&m1,&m2,&t1,&t2,&w1,&w2,&th1,&th2,&f1,&f2,&sa1,&sa2);
    printf("%20s  %d %d", city, s1,s2);
  } else {
    printf("\n"); 
    break;
  }  //Break infinite loop because for loop broke from EOF
}

Sample output:

           Baltimore 75 60
Miami  20 10
Washington D.C.  75 50
New York  75 50

only Baltimore is being right aligned. Any help is appreciated.

4

1 回答 1

5

"%c"scanf 模式不会跳过空格,因此您的城市字符串中可能会出现空格。特别是,由于您从不扫描前一行\n末尾的换行符 ( ),因此您的城市名称都将以换行符开头(第一个除外)。此外,您printf从不打印任何换行符(城市中的换行符除外),因此可以解释您所看到的内容。

更准确地说 - 您的第二个城市被读取为"\nMiami"(6 个字符),所以当它打印出来时"%20s",它首先打印 14 个空格。这些空格都打印Baltimore在行尾(因为行尾没有打印换行符),然后打印"\nMiami"

尝试使用:

for (i = 0; fscanf(input,"%c", &c)!=EOF && c!='#';) {
    if (i == 0 && isspace(c)) continue;
    city[i++] = c; }
while (i>0 && isspace(city[i-1])) i--;

从城市名称中去除前导和尾随空格。

于 2013-02-19T19:20:11.987 回答