n00b在这里。我的fscanf
功能遇到了一些困难。我试图从文本文件中读取一个字符串,但程序永远不会返回0.我认为do-while循环有问题,可能带有EOF
标志,但我可以&#39了解什么是错的。该文件是:
dog 10 20 30
cat 20 10 30
以下是源代码:
char word[15], match[15];
int res;
do {
cout << "Word: ";
gets(word);
if (word!=".") {
fd=fopen("memory.txt","r");
do {
fscanf(fd,"%s",match);
} while ((word!=match)||(res!=EOF));
fclose(fd);
};
} while (word!=".");
答案 0 :(得分:0)
您的代码中存在许多错误,其中大部分都已在评论中指出。
以下是更正后的版本:
char word[15], match[15];
for (;;) {
printf("Word: ");
if (scanf("%14s", word) != 1 || !strcmp(word, "."))
break;
int found = 0;
FILE *fd = fopen("memory.txt", "r");
if (fd != NULL) {
while (fscanf(fd, "%14s", match) == 1) {
if (!strcmp(word, match)) {
found = 1;
break;
}
}
fclose(fd);
}
if (found) {
printf("found\n");
} else {
printf("not found\n");
}
}