我有以下输入文件:
WO98EKOYMPCAUEWT0 Honda Civic 2011 4
7W32UAERZFBCB3S6P Chevrolet Tahoe 2011 6
DNU7XQO8LLA9I6YFX Toyota Tercel 2012 4
DNU7XQO8LLA9I6YFX Toyota Tercel 2012 4
DNU7XQO8LLA9I6YFX Toyota Tercel 2012 4
7W32UAERZFBCB3S6P Chevrolet Tahoe 2011 6
这实际上是我们交付的一项任务,我已经挣扎了几天而没有结果。
读取每一行并将第二,第三和第四的值放在结构中。
之后添加一个新列,它是基于上面3列的出现次数。
按秒,第三和第四排序数据。然后将它们输出到文件中。
到目前为止,这是我的代码:
struct Car
{
char *CarMake;
char *CarModel;
char *CarMakeYear;
int Occurances;
};
int main(int argc, char *argv[])
{
//File related
FILE *inputFile, *outputFile;
char fileName[] = "";
//Struct related
int carCounter = 0;
struct Car cars[50];
struct Car car;
car.CarMake = (char*)malloc( 200 *sizeof(char));
car.CarMakeYear = (char*)malloc( 200 *sizeof(char));
car.CarModel = (char*)malloc( 200 *sizeof(char));
car.Occurances = 0;
printf("Please enter file name:", fileName);
scanf("%s",fileName);
inputFile = fopen(fileName,"r");
while(fscanf(inputFile, "%*s %s %s %s %*s\n",car.CarMake, car.CarModel,car.CarMakeYear ) != EOF)
{
cars[carCounter].CarMake = car.CarMake;
carCounter++;
}
fclose(inputFile);
int i=0;
for(i=0;i<6;i++)
printf("%s %s %s \n", cars[i].CarMake, cars[i].CarModel,cars[i].CarMakeYear);
system("PAUSE");
return 0;
}
上面的printf将采用最后一个数组值并保持打印,这意味着它无法正常工作。有人请帮忙,我要到午夜才提交。
答案 0 :(得分:5)
cars[carCounter].CarMake = car.CarMake;
这一行是问题所在。在C中,您不能简单地使用赋值运算符复制字符串。您必须为字符串分配一个新缓冲区并将其复制:
cars[carCounter].CarMake = malloc(strlen(car.CarMake) + 1); // plus one to include the null-terminator
strcpy(cars[carCounter].CarMake, car.carMake);
根据您使用的平台/编译器,您可以使用strdup
函数,它基本上完全相同:
cars[carCounter].CarMake = strdup(car.CarMake);
完成后不要忘记free
记忆。
修改强>
从用户输入中获取文件名还有另一个问题。 char fileName[] = "";
行不会为实际文字留下任何空间 - 请尝试char fileName[100];
之类的内容。即使现在有效,也不能保证继续工作;依靠未定义的行为,永远不会安全。
答案 1 :(得分:0)
我会这样写:
struct Car
{
char *CarMake;
char *CarModel;
char *CarMakeYear;
int Occurances;
};
int main(int argc, char *argv[])
{
//File related
FILE *inputFile, *outputFile;
char fileName[] = "";
//Struct related
int carCounter = 0;
struct Car cars[50];
struct Car car;
car.CarMake = (char*)malloc( 200 *sizeof(char));
car.CarMakeYear = (char*)malloc( 200 *sizeof(char));
car.CarModel = (char*)malloc( 200 *sizeof(char));
car.Occurances = 0;
printf("Please enter file name:", fileName);
scanf("%s",fileName);
inputFile = fopen(fileName,"r");
while(fscanf(inputFile, "%*s %s %s %s %*s\n",car.CarMake, car.CarModel,car.CarMakeYear ) != EOF)
{
cars[carCounter].CarMake = car.CarMake;
//-- change starts here
// the values of the car struct being pointed to by the current carCounter array placeholder
// you allocate a new car so that you won't be touching the old ones.
car.CarMake = (char*)malloc( 200 *sizeof(char));
car.CarMakeYear = (char*)malloc( 200 *sizeof(char));
car.CarModel = (char*)malloc( 200 *sizeof(char));
//-- change ends here
carCounter++;
}
fclose(inputFile);
int i=0;
for(i=0;i<6;i++)
printf("%s %s %s \n", cars[i].CarMake, cars[2].CarMake,cars[3].CarMake);
system("PAUSE");
return 0;
}