【发布时间】:2014-08-24 01:04:00
【问题描述】:
似乎无法弄清楚为什么此代码不起作用。 它应该非常直截了当。 根据我的故障排除,在 while(token) 块中分配了 id 数组,但是当我去打印 while(token) 块之外的所有 char 数组时,id 数组只显示所有其他数组的内容。
int loadCatData(char* menuFile) {
char line[MAX_READ];
char id[ID_LEN];
char hotCold[MIN_DESC_LEN];
char name[MAX_NAME_LEN];
char description[MAX_DESC_LEN];
char delim[2] = "|";
char lineTemp[MAX_READ];
int count;
FILE *mfMenu = fopen(menuFile, "r");
while (fgets(line, sizeof(line), mfMenu)!=NULL) {
count = 0;
printf(line);
strcpy(lineTemp,line);
char* token = strtok(lineTemp, delim);
while (token) {
printf(token);
if (count == 0) {
strcpy(id, token);
}
if (count == 1) {
strcpy(hotCold, token);
}
if (count == 2) {
strcpy(name, token);
}
if (count == 3) {
strcpy(description, token);
}
printf("\n");
token = strtok(NULL, delim);
count = count + 1;
}
printf(id);
printf(hotCold);
printf(name);
printf(description);
}
fclose(mfMenu);
return true;
}
【问题讨论】:
-
你确定token是复制到id的数组还是不为空?
-
无论如何,对于第二个、第三个和第四个选项,在 while 循环中执行 else if,因为否则,每次,即使“正确”的主体 if 语句已被执行,其他 if 语句也将被检查,但这不是必需的。
-
@usr: 使用
else if并不比看似冗余的if检查快,因为任何合理的编译器都会在这两种情况下以相同的方式优化代码。 -
好的,谢谢分享,没想到;)