2014-12-03 109 views
-1

正如标题所说,当调用beolvas()时,我会崩溃。你可能会得到我想要做的,这也很简单。我正在使用mingw32 btw。感谢您提前提供任何帮助!C文件输入fscanf问题(崩溃)

typedef struct 
{ 
    int kerSzam; 
    int voteCount; 
    char *lastName; 
    char *firstName; 
    char *party; 
} Vote; 

void beolvas(Vote t[], int *n) 
{ 
    FILE *in; 
    in = fopen("szavazatok.txt", "r"); 

    while(!feof(in)) 
    { 
     fscanf(in, 
       "%d %d %s %s %s\n", 
       &t[*n].kerSzam, 
       &t[*n].voteCount, 
       t[*n].lastName, 
       t[*n].firstName, 
       t[*n].party 
       ); 

     (*n)++; 
    } 

    fclose(in); 
} 

szavazatok.txt看起来是这样的:

2 53 first last zed 
1 5 first last pet 
... 
+3

您必须为结构的char *成员分配一些内存...... – 2014-12-03 20:06:56

+0

需要进一步的帮助吗? – chux 2017-05-08 14:02:14

回答

1

正如@让 - 巴蒂斯特Yunès评价说,需要为字符串分配内存。

推荐测试fscanf()的结果。

void beolvas(Vote t[], int *n, int maxn) { 
    FILE *in; 
    in = fopen("szavazatok.txt", "r"); 
    if (in) { 
    char lastName[50]; 
    char firstName[50]; 
    char party[50]; 
    int cnt = 0; 

    // spaces not needed in format, but widths are very useful 
    while(*n < maxn && (cnt = fscanf(in, "%d%d%49s%49s%49s", 
     &t[*n].kerSzam, &t[*n].voteCount, lastName, firstName, party)) == 5) { 
     t[*n].lastName = strdup(lastName);  
     t[*n].firstName = strdup(firstName);  
     t[*n].party = strdup(party);  
     (*n)++; 
    } 

    fclose(in); 
    } 
} 

由于strdup()是非标准的,在这里,如果需要的是一种实现。

char *strdup(const char *src) { 
    if (src) { 
    size_t size = strlen(src) + 1; 
    char *p = malloc(size); 
    if (p) { 
     return memcpy(p, src, size); 
    } 
    } 
    return 0; 
}