2012-11-19 45 views
1

在這個程序中它編譯,但我得到分段錯誤,sscanf(str, "%d %s %s %d %f", &pos, z[pos-1].city, z[pos-1].state, &z[pos-1].population, &z[pos-1].growth);其由於該行z[pos-1].city, z[pos-1].state,可是沒有&但是當我補充一點,我得到警告:format â%sâ expects type âchar *â, but argument 4 has type âchar (*)[200]âÇ解析與fgets()字符數組轉換成多個變量與sscanf的使用結構

我敢肯定還有另一種方法做到這一點,我需要使用結構,讀取文件存儲信息到一個結構數組然後顯示數組。 printf只是將城市和州存儲到char數組中。

我評論了我嘗試初始化爲數組的區域,並且使用char數組值的全部三個不兼容類型:a,'a',「a」。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

typedef struct{ 
    int rank; 
    char city[200]; 
char state[50]; 
int population; 
float growth; 
}city_t; 

void read_data(city_t *z) 
{ 
    FILE *inp; 
    inp = fopen("cities.dat", "r"); 
    char str[256]; 
    int pos = 0; 
    if(inp==NULL) 
    { 
     printf("The input file does not exist\n"); 
    } 
    else 
    { 
     /*reads and test until eof*/ 
     while(1) 
     { 
      /*if EOF break while loop*/ 
      if(feof(inp)) 
      {break;} 
      else 
      { 
       /*read in a number into testNum*/ 
       //fscanf(inp, "%d", &testNum); 
       fgets(str,sizeof(str),inp); 
       sscanf(str, "%d %s %s %d %f", &pos, z[pos-1].city, z[pos-1].state, &z[pos-1].population, &z[pos-1].growth); 
       z[pos-1].rank = pos; 
      } 
     } 
    } 
    fclose(inp); 
} 

void print_data(city_t *z, int size) 
{ 
    int i; 
    printf("rank\tcity\t\tstate\tpopulation\t\tgrowth\n"); 
    for(i=0;i<size;i++) 
    { 
     printf("%d\t%s\t\t%s\t\%d\t\t%f\n", z[i].rank, z[i].city, z[i].state, z[i].population, z[i].growth); 
    } 
} 

int main() 
{ 
    int i; 
    city_t cities[10]; 
    /*for(i;i<10;i++) 
    { 
     cities[i].rank = 0; 
     cities[i].city = "a"; 
     cities[i].state = "a"; 
     cities[i].population = 0; 
     cities[i].growth = 0.00; 
    }*/ 
    read_data(&cities[0]); 
    print_data(&cities[0], 10); 
    return(0); 
} 

{ 
dat file 
1 New_York NY 8143197 9.4 
2 Los_Angeles CA 3844829 6.0 
3 Chicago IL 2842518 4.0 
4 Houston TX 2016582 19.8 
5 Philadelphia PA 1463281 -4.3 
6 Phoenix AZ 1461575 34.3 
7 San_Antonio TX 1256509 22.3 
8 San_Diego CA 1255540 10.2 
9 Dallas TX 1213825 18.0 
10 San_Jose CA 912332 14.4 
} 

回答

0

在的read_data,你掃描到z[pos-1]....若pos從0開始。所以,你會寫超越(前)在延長陣列。

只要做一個全球替換pos-1pos和也增量pos;你也可以使用fscanf,所以你的閱讀可以是這樣的:

for (int pos=0; !feof(inp); ++pos) 
{ 
    fscanf(inp, "%d %s %s %d %f", 
      &z[pos].rank, 
      z[pos].city, 
      z[pos].state, 
      &z[pos].population, 
      &z[pos].growth); 
} 
+0

謝謝你是一個真正簡單的修復,我花了太長的時間:) – user1834476