为什么 strtok() 使我的程序 return 负值?
Why does strtok() make my program return negative value?
我有一个程序,我想在其中从文件中读取文本,然后将其存储在一个结构数组中。我试着用 strtok() 来做。这是代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct kon {
char name[50];
int year;
char city[50];
};
typedef struct kon kon;
int main(void) {
FILE *input;
input = fopen("kon.txt", "r");
if (!input) {
printf("No such file");
}
else {
kon *tab;
char line[256], year_tmp[10], *token;
int counter = 0, max_tab = 2, year;
tab = (kon*)malloc(max_tab * sizeof(kon));
while(fgets(line, sizeof(line), input) != EOF) {
if(line) {
token = strtok(line, ", ");
strcpy(tab[counter].name, token);
token = strtok(NULL, ", ");
strcpy(year_tmp, token);
year = atoi(year_tmp);
tab[counter].year = year;
token = strtok(NULL, ", ");
strcpy(tab[counter].city, token);
printf("%s, %d, ", tab[counter].name, tab[counter].year);
printf("%s\n", tab[counter].city);
counter++;
}
/* Reallocing memory for array if needed */
if(counter == max_tab - 1) {
max_tab += 2;
tab = realloc(tab, max_tab * sizeof(kon));
}
}
printf("%d", max_tab);
free(tab);
fclose(input);
}
return 0;
}
这是文本文件:
RUMIANEK, 1998, Warsaw,
ALAMOS, 1991, Madrid,
BOSSIER, 2004, Paris,
还有很多,但我把它缩短了一点,最后有一个空行。
这是一个输出:
RUMIANEK, 1998, Warsaw
ALAMOS, 1991, Madrid
BOSSIER, 2004, Paris
Process returned -1073741819 (0xC0000005) execution time : 2.122 s
Press any key to continue.
如您所见,我的程序在 while 循环后没有 return max_tab,我不知道为什么。
@编辑:
添加了完整代码。
这里:
while(fgets(line, sizeof(line), input) != EOF)
去掉 EOF。
然后你可能明白这个 if(line)
是不需要的,因为它总是评估为真。
我有一个程序,我想在其中从文件中读取文本,然后将其存储在一个结构数组中。我试着用 strtok() 来做。这是代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct kon {
char name[50];
int year;
char city[50];
};
typedef struct kon kon;
int main(void) {
FILE *input;
input = fopen("kon.txt", "r");
if (!input) {
printf("No such file");
}
else {
kon *tab;
char line[256], year_tmp[10], *token;
int counter = 0, max_tab = 2, year;
tab = (kon*)malloc(max_tab * sizeof(kon));
while(fgets(line, sizeof(line), input) != EOF) {
if(line) {
token = strtok(line, ", ");
strcpy(tab[counter].name, token);
token = strtok(NULL, ", ");
strcpy(year_tmp, token);
year = atoi(year_tmp);
tab[counter].year = year;
token = strtok(NULL, ", ");
strcpy(tab[counter].city, token);
printf("%s, %d, ", tab[counter].name, tab[counter].year);
printf("%s\n", tab[counter].city);
counter++;
}
/* Reallocing memory for array if needed */
if(counter == max_tab - 1) {
max_tab += 2;
tab = realloc(tab, max_tab * sizeof(kon));
}
}
printf("%d", max_tab);
free(tab);
fclose(input);
}
return 0;
}
这是文本文件:
RUMIANEK, 1998, Warsaw,
ALAMOS, 1991, Madrid,
BOSSIER, 2004, Paris,
还有很多,但我把它缩短了一点,最后有一个空行。
这是一个输出:
RUMIANEK, 1998, Warsaw
ALAMOS, 1991, Madrid
BOSSIER, 2004, Paris
Process returned -1073741819 (0xC0000005) execution time : 2.122 s
Press any key to continue.
如您所见,我的程序在 while 循环后没有 return max_tab,我不知道为什么。
@编辑:
添加了完整代码。
这里:
while(fgets(line, sizeof(line), input) != EOF)
去掉 EOF。
然后你可能明白这个 if(line)
是不需要的,因为它总是评估为真。