我面临C. 一个很有趣的问题,所以我有一个结构,看起来像这样:阵列 - ç坏价值
struct Question {
int year;
char* month;
char* day;
char* hour;
char* minute;
char* second;
char* question;
int answerCount;
char* answers[1024];
} questions[100];
在那里,我初始化问题结构的数组所谓的问题,用100
大小所以我想,以填补从文件看像这样的数组:
2017 04 01 12 38 00 OK? 2 NO NO
2017 04 01 14 15 00 WHAT? 4 YES YES YES YES
结构: 年月日时分秒问题answercount回答
我处理这样的文件:
...
int id = 0;
int j;
char line[2048];
while ((fgets(line, sizeof(line), fp)) != NULL) {
char* p = strtok(line, " ");
char* tokens[1024];
char* token;
int i = 0;
int counter = 0;
while((p != NULL)) {
switch(counter) {
case 0: questions[id].year = atoi(p); break; // year
case 1: questions[id].month = p; break; // month
case 2: questions[id].day = p; break; // day
case 3: questions[id].hour =p; break; // hour
case 4: questions[id].minute = p; break; // minute
case 5: questions[id].second = p; break; // seconds
case 6: questions[id].question = p; break; // question
case 7:
questions[id].answerCount = atoi(p);
int qcount = atoi(p);
int k;
int l = j;
//printf("count : %d", qcount);
for (k = 0; k < qcount; ++k) {
p = strtok(NULL, " ");
++l;
questions[id].answers[k] = p;
}
break;
default: break;
}
p = strtok(NULL, " ");
++counter;
}
++id;
}
fclose(fp);
...
之后,如果我的printf在while循环的问题[0]。提问元素,我得到的,但是如果我打印出“OK?” while循环之后的同样的东西,我得到“什么?”。
我花了很多时间思考我可能会做错什么,但没有成功。
感谢您的帮助。
所以你期望字符串“OK?”存储在某个地方以供以后打印。哪里? –
那么在问题[0] .question。我在这里进行分配:questions [id] .question = p; – Corner
提问[0] .question是一个指针。它不能存储字符串,它只能指向其他地方存储的字符串。 –