我需要读取一个文本文件并将数据存储在一个结构中。我已经完成了使用 fgets(buffer, sizeof(buffer), fp) 使用
读取数据。我的文件结构如下FILE *fp = fopen("datafile.txt", "r")
打开文件的部分
John is enrolled in MATH 1314
Steve is enrolled in MATH 1314
struct course {
char name[20];
char department[4];
int number[4];
};
int main(void)
{
FILE *fp;
char* token;
char* line[50];
struct course student;
fp = fopen("input-hw04b.txt", "r");
while (fgets(line, sizeof(line), fp) != NULL)
{
token = strtok(buffer, " ");
while (token != NULL)
{
/* Add structures here */
token = strtok(NULL, " ");
}
}
}
我需要存储以下内容
- 学生姓名中的约翰
- 学生系数学
- 学生编号 1314
到目前为止,这就是我所拥有的,我一直困惑于如何将这些数据放入结构中。我从文本文件中提取数据,逐行读取数据,然后对其进行标记,以便我尝试将其放入结构中。
最佳答案
以下是基于您现有代码的一些提示。
int count = 0;
token = strtok(buffer, " ");
while (token != NULL)
{
if (count == 0)
{
strncpy(student.name, token, 20);
student.name[19] = '\0'; // ensure null termination
}
else if (count == 1)
{
/* validate "is" */
if (strcmp(token, "is") != 0)
break;
}
else if (count == 2) { /*validate "enrolled"*/ }
else if (count == 3) { /* validate "in"*/ }
else if (count == 4)
{
// set the department field
}
else if (count == 5)
{
// set the number field
}
count++;
token = strtok(NULL, " ");
}
当然,这个示例不能处理一些鲁棒性问题(例如,名称可能 >= 超过 20 个字符,或者字符串中可能只有 3 个单词,等等...)。但应该让你开始......
关于C:逐行读取文件并将数据插入到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24624600/