【发布时间】:2020-09-11 15:33:34
【问题描述】:
我无法将文件读入包含enum 的typedef struct。我是C的初学者,所以我真的不知道如何用枚举读取文件。
我能够读取文件并用简单的代码打印出内容,但我需要读取文件并将该行中的每个字符串分配给 typedef 结构中的类型。
输入文件如下所示:
random.num year model category
Example:
54 2012 model1 type1
这些是我的代码的相关部分:
typedef enum { type1, type2, type3, type4} category;
typedef struct {
int num;
int year;
char make[MAX_MAKE_CHARS];
category category; //enum from above
}item;
//reading in the file I have this:
int create_db(char *f){
char file_contents[100]; // read the file --> ("r") FILE *f = fopen(f, "r");
// check if file can be used
if(f == NULL){
printf("File not found");
exit(1);
}
int i = 0; item item_array[100];
while(fscanf(f, "%d %d %s %s", &item[i].num, &item[i].year, item[i].make, item[i].category) != EOF){
// can't get past the while look where it says "item[i].category
我得到错误:
格式“%s”需要“char *”类型的参数,但参数 6 的类型为“category * {aka enum *}”
由于我对 C 完全陌生,我对如何将文件读入结构感到困惑。我该怎么办item[i].category?
【问题讨论】:
-
可以读取字符串。你不能读这样的枚举。编译器会从程序中删除枚举名称,因此在程序运行时无法保留它们。
-
有没有办法扫描文件以读取信息,但仍然像其他的一样使用结构中的类别?
-
需要读入一个
char数组并手动解析内容。