我从一个文件读入一个结构数组,然后逐个打印出来!
在文件中看起来像这样!
1: När kom potatisen till Europa?;A:1300-talet;B:1500-talet;C:900-talet;D:1700-talet;B
D
2: I vilken enhet mats elektrisk spänning ?;A:Ampere;B:Volt;C:Joule;D:Watt
B
3: Från vilket land har vi fått lego?;A:Tyskland;B:Australien;C:Japan;D:Danmark
D
这是我的代码!
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct quiz
{
char questions[50];
char* alt[4];
char correctanswer[1];
};
int main() {
struct quiz all_ques[50];
int i = 0;
char answer;
FILE *haidar;
haidar = fopen("gameee.txt", "r");
char str[500];
char *ptr;
while (fgets(str, sizeof(str), haidar)) // read 500 characters
{
ptr = strtok(str, ";"); // split our findings around the " ;"
if (ptr == NULL) {
}
else {
strcpy(all_ques[i].questions, ptr); // store the question
}
ptr = strtok(NULL, ";"); // and keep splitting
if (ptr == NULL) {
}
else {
all_ques[i].alt[0] = malloc(10);
strcpy(all_ques[i].alt[0], ptr);// store the first option
}
ptr = strtok(NULL, ";"); // and keep splitting
if (ptr == NULL) {
}
else{
all_ques[i].alt[1] = malloc(10);
strcpy(all_ques[i].alt[1], ptr); // store the second option
}
ptr = strtok(NULL, ";"); // and keep splitting
if (ptr == NULL) {
}
else {
all_ques[i].alt[2] = malloc(10);
strcpy(all_ques[i].alt[2], ptr); // store the third option
}
ptr = strtok(NULL, ";"); // and keep splitting
if (ptr == NULL) {
}
else {
all_ques[i].alt[3] = malloc(10);
strcpy(all_ques[i].alt[3], ptr); // store the fourth option
}
while (fgets(str, 500, haidar)== NULL); {
printf("error\n");
}
if (str == NULL) {
printf("error\n");
}
else{
strcpy(all_ques[i].correctanswer, str); // store the correct answer
fgets(str, sizeof(str), haidar); // read one line (and throw it away)
i++;
}
}
printf("%s\n%s\n%s\n%s\n%s\n", all_ques[0].questions, all_ques[0].alt[0], all_ques[0].alt[1], all_ques[0].alt[2], all_ques[0].alt[3],ptr);
answer = (getch());
if (answer == all_ques[0].correctanswer[0]) {
printf("right\n");
}
else
printf("wrong\n");
printf("%s\n%s\n%s\n%s\n%s\n", all_ques[1].questions, all_ques[1].alt[0], all_ques[1].alt[1], all_ques[1].alt[2], all_ques[1].alt[3], ptr);
answer = (getch());
if (answer == all_ques[1].correctanswer[0]) {
printf("right\n");
}
else
printf("wrong\n");
}
我想打印出问题,然后打印出用户可以选择的替代方案,依此类推。但是当我在vs 2013中运行它时出现此错误
Debug assertion failed!
line 57
expression (str!=NULL)
但是没有57行!请帮忙
最佳答案
该代码有几个严重的问题:
第64行删除;
,这里有无限循环!
将str
与NULL
进行比较没有用(这总是错误的!),这似乎在运行时引起您的问题(我的编译器在编译时抱怨)
两个printf
第78和88行的参数过多(请重新考虑格式...)。
更正后,它似乎可以正常工作(至少我能够回答两个问题)...