从文件到C中的结构 [英] From file to structure in C
问题描述
我试图从文件写入到C中的结构中。每当我尝试在结构中赋值时,会给出错误:赋值中的不兼容类型。
我的结构看起来像这样:
struct competition {
char eventTitle [79];
char date [79];
char time [79];
};
基本上我想打开文件并在结构中分配不同的值。即。第一行在文件 - > eventTitle,第二行 - >日期,第三行 - >时间。
以下是我如何分配它:
FILE * naDaSt;
char * mode =r;
int lines = 0;
char line [79],current [79];
naDaSt = fopen(nameDateStart,mode);
if(naDaSt == NULL){
printf(Can not find the files。);
exit(1);
} else {
struct competition comp,* p;
p =& comp;
while(fgets(line,79,naDaSt)){
lines ++;
if(lines == 1){
p-> eventTitle = line;
}
if(lines == 2){
p-> date = line;
}
if(lines == 3){
p-> time = line;
code $ pre
$ b }
任何人都可以帮助我吗?根本原因:
解决方案您不能这样做:
p-> eventTitle = line;
p-> date = line;
p-> time = line;
您正尝试使用不能完成的赋值来分配数组,数组需要被复制。编译器正确地报告错误:
pre $ 错误:赋值中的不兼容类型
因为确实类型你试图 assign 是不兼容的。
解决方案:
您需要使用 strcpy ,然后复制字符数组并将其分配。
I am trying to write from file to structure in C. Whenever I try to assign value in structure it gives me error: incompatible types in assignment.
My structure looks like this:
struct competition{
char eventTitle[79];
char date[79];
char time[79];
};
Basically I want to open the file and assign individual line to different value in structure. ie. first line in file -> eventTitle, second line -> date, third line -> time.
Here is how I try to assign it:
FILE *naDaSt;
char *mode = "r";
int lines = 0;
char line[79], current[79];
naDaSt = fopen(nameDateStart, mode);
if(naDaSt == NULL){
printf("Can't find the files.");
exit(1);
}else{
struct competition comp, *p;
p = ∁
while(fgets(line, 79, naDaSt)){
lines++;
if(lines == 1){
p->eventTitle= line;
}
if(lines == 2){
p->date = line;
}
if(lines == 3){
p->time = line;
}
}
}
}
Could anyone help me?
解决方案 Root Cause:
You cannot do this:
p->eventTitle = line;
p->date = line;
p->time = line;
You are trying to assign arrays using assignment which cannot be done, arrays need to be copied. The compiler rightly reports the error:
error: incompatible types in assignment
because indeed the type you are trying to assign are incompatible.
Solution:
Instead, You need to use strcpy and copy the character arrays and not assign them.
这篇关于从文件到C中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文