[英]Reading in character strings from text file in C
I need to write a program that reads in strings from a text file and stores each word in a struct, ie if the first line in the text file is: 我需要编写一个程序,该程序从文本文件中读取字符串并将每个单词存储在结构中,即,如果文本文件中的第一行是:
TOYOTA COROLLA 2014 WHITE 丰田COROLLA 2014白色
Toyota would go into structname.model, corolla would go into structname.make, etc. I am having trouble with reading each string into their according element in the struct. Toyota将进入structname.model,花冠将进入structname.make,等等。我在将每个字符串读入结构中的相应元素时遇到了麻烦。 My source code (which I have not posted here bc it is very long and a large percentage of it is pretty irrelevant to this problem) compiles with no errors, but I am 99% sure it is a problem with my loop which is supposed to be reading in the values:
我的源代码(我没有在这里发布它的代码很长,并且很大一部分与这个问题无关)可以正确编译,但是我有99%的肯定是我的循环有问题,应该是正在读取以下值:
carRecord cars[10]; //declares array of structs containing carRecord info
char filename[256];
char buf[256];
FILE *carfile;
printf("Please enter the name of a file to read car records from (followed by the file extension): ");
scanf("%s", filename);
carfile = fopen(filename, "r");
if (!carfile)
{
printf("File failed to open.\n");
}
printf("ERROR CHECK 1");
int i = 0;
while ((fgets(buf, sizeof(buf), carfile) != NULL) && i < 10)
{
cars[i].make = strdup(strtok(buf, " "));
cars[i].model = strdup(strtok(buf, " "));
cars[i].year = atoi(strdup(strtok(buf, " ")));
cars[i].color = strdup(strtok(buf, " "));
i++;
}
The first error check prints, and then the program crashes. 打印第一个错误检查,然后程序崩溃。 I have a strong, scary feeling this has to do with the malloc command, but I am pretty new to C and have absolutely no idea how to implement it.
我有一种强烈的恐惧感,这与malloc命令有关,但是我对C还是很陌生,并且完全不知道如何实现它。
If at all helpful, the struct declaration for carRecord is: 如果有帮助,carRecord的结构声明为:
struct carRecord{
char* make; //make of car
char* model; //model of car
int year; //year of car
char* color; //color of car
};
(EDIT: code has been updated to reflect below comments) (编辑:代码已更新,以反映以下评论)
I am pretty sure, if you allocate memory to the structure elements, you'll get desired result. 我很确定,如果您将内存分配给结构元素,您将获得理想的结果。 Else, as you mentioned, use calloc/malloc.
如您提到的,否则,请使用calloc / malloc。
struct carRecord{
char make[100]; //make of car
char model[100]; //model of car
int year; //year of car
char color[100]; //color of car
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.