我有一个名为question.txt的.txt文件,其中包含多项选择题和多个答案,格式如下:
**X question content
# Answer 1
# Answer 2
...
# Answer n
- X是一个整数(问题所在章节的数字(
- n小于或等于5
我试图提取关于章节号(X(的信息、问题内容和所述问题的答案,并将它们存储到类似的结构变量中
struct {
int chapter;
int qcontent[512];
char answer[5][256];
}
下面是我的尝试,我想知道是否有不同的方法,也许是更紧凑的方法
#include <stdio.h>
typedef struct {
int chapter;
char qcontent[512];
char answer[5][256];
} question;
int main()
{
question question[100];
FILE *fp = fopen("question.txt", "r");
char fline[512];
int i = -1; // Count question
int j = 0; // Count answer in a question
while (!feof(fp)) {
fgets(fline, 512, fp);
fline[strlen(fline) - 1] = 0;
if (strstr(fline, "**")) {
++i;
question[i].chapter = fline[2] - '0';
strcpy(question[i].qcontent, fline + 4);
j = 0;
}
if (strstr(fline, "#")) {
strcpy(question[i].answer[j++], fline + 2);
}
}
return 0;
}
注意:您提供的代码中有许多错误。然而,我将展示一种处理此类案件的方法。
首先,您需要了解结构信息是如何保存在文件中的。比方说,我们有以下格式。
chapter, question, ans1, ans2, ans3, ans4, ans5
datatype: int, char*, char*, char*, char*, char*, char*
意思是,我们用逗号分隔每个元素。如果question
或answer
元素包含逗号,则可能会出现问题。在这种情况下,只需找到像|,
这样的符号,它们不太可能出现在question
或answer
中。我们将用来演示示例的文件是这个
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct {
int chapter;
char qcontent[512];
char answer[5][256];
} question;
int main(){
question question[100];
FILE *file = fopen("question.txt","r");
char buffer[2048];
memset(buffer, 2048, 0); // initializing the buffer with 0, its always a good practice to initialize.
int i=0;
while(fgets(buffer, 2048, file)!=NULL){
// atoi() = ascii to integer, a function frob stdlib.h
question[i].chapter = atoi(strtok(buffer, "n,"));
strcpy(question[i].qcontent, strtok(NULL, ","));
for(int j=0; j<4; j++){
strcpy(question[i].answer[j], strtok(NULL, ","));
}
// The last string will have a n next to it, so-
strcpy(question[i].answer[4], strtok(NULL, ",n"));
i++;
}
for(int index=0; index<i; index++){
printf("Question on chapter %d:n",question[index].chapter);
printf("%sn",question[index].qcontent);
printf("Answers:n");
for(int j=0; j<5; j++) printf("%sn",question[index].answer[j]);
}
return 0;
}
您将在屏幕中看到此输出。
你可以在这里了解更多。
如何从文件中读取/写入2D数组?
strtok((是如何工作的?
fgets((是如何工作的?
atoi((是如何工作的?