在C中,我试图从文件中获取一个学生信息,并尝试将信息纳入struct,但它不起作用
我的结构格式就是这样
struct {
char student_ID[11];
char full_name [MAX];
char program [MAX];
char year;
char e_mail [MAX*2];
char status;
} student_info;
,这是我的功能,它试图获取一个学生信息
void scanStudents(FILE *file, student_info *student) {
char get_line [500];
fgets(get_line,500,file);
char *ID = strtok(get_line,";");
strcpy(student->student_ID, ID);
char *NAME = strtok(get_line, ";");
strcpy(student->full_name, NAME);
char *PROGRAM = strtok(get_line,";");
strcpy(student->program, PROGRAM);
char *YEAR = strtok(get_line, ";");
strcpy(student->year,YEAR);
char *E_MAIL = strtok(get_line, ";")
strcpy(student->e_mail,E_MAIL);
char *STATUS = strtok(get_line,";");
strcpy(student->status, STATUS);
}
我在其他函数中打开文件,并调用此功能,因为我的目标是尝试将学生信息存储在一个阵列中,该数组是student_ınfo。 TXT文件包含许多学生信息
31300000010;DURU AY;Computer Engineering;2;[email protected];
my struct format is like this
struct {
char student_ID[11];
char full_name [MAX];
char program [MAX];
char year;
char e_mail [MAX*2];
char status;
} student_info;
And this is my function which tries to get one student information
void scanStudents(FILE *file, student_info *student) {
char get_line [500];
fgets(get_line,500,file);
char *ID = strtok(get_line,";");
strcpy(student->student_ID, ID);
char *NAME = strtok(get_line, ";");
strcpy(student->full_name, NAME);
char *PROGRAM = strtok(get_line,";");
strcpy(student->program, PROGRAM);
char *YEAR = strtok(get_line, ";");
strcpy(student->year,YEAR);
char *E_MAIL = strtok(get_line, ";")
strcpy(student->e_mail,E_MAIL);
char *STATUS = strtok(get_line,";");
strcpy(student->status, STATUS);
}
I open file in other function and by calling this function in that my aim is try to store student informations in one array which type is student_ınfo. The txt file contains many student information in type of
31300000010;DURU AY;Computer Engineering;2;[email protected];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个示例,包括@retired ninja和@gerhardh所说的错误修复。
文件内容是:
现在,该文件用于将每个字段存储为字符串。我对您的代码进行的修复程序如下:
student_info
声明及其定义是固定的。年
和状态
字段,以便它们遵守最小字符串空间要求。temp
来保存由strtok
函数返回的指针地址。此示例代码仅供参考。因此,您将此代码背后的想法调整为实际代码。
这是示例代码的输出:
Here is an example including error fixes that @Retired Ninja and @Gerhardh stated.
The file content is:
Now this one is for storing each field as string. The fixes I made to your code are the following:
student_info
declaration and its definition are fixed.year
andstatus
fields so that they comply the minimum string space requirements.temp
to hold the pointer address which is returned bystrtok
function.This sample code is for reference only. So you adapt the idea behind this code to your actual code.
This is the output of the sample code: