Tony Abboud
Tony Abboud

Reputation: 23

String is off by 1 character - C

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.

Upvotes: 2

Views: 120

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126448

The "%c" scanf pattern does not skip whitespace, so you're likely getting whitespace in your city strings. In particular, as you never scan past the newline (\n) at the end of the previous line, your city names would all start with newlines (except for the first one). In addition, your printf never prints any newlines (other than the ones in the cities), so that explains what you are seeing.

More precisely -- your second city gets read as "\nMiami" (6 characters), so when its printed out with "%20s", it prints 14 spaces first. Those spaces are all printed on the end of the Baltimore line (as there is no newline printed at the end of it), and then it prints "\nMiami"

Try using:

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--;

to strip leading and trailing whitespace from the city name.

Upvotes: 5

Related Questions