【发布时间】:2022-01-06 16:07:06
【问题描述】:
我试图编写一个程序来搜索文件中的单词,这是我写的,但它不起作用。 我希望该程序读取在空格中缩放的文本部分。 当我运行它并写下“Hello”时,我什么都不做并结束,但我想要它,以便输出是:
Hello
coolcool
horse
miein
Hello
cookiecookie
horse
lol
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define max 30
int main() {
FILE *file;
char c[max + 1];
int x;
char input[max + 1];
char suche[max + 1];
char output[max + 1];
printf("Please write the word to search ");
fgets(input, max, stdin);
file = fopen("Testo.dat", "r");
//here does the programm fail
while (feof(file) != 0) {
fgets(suche, max, file);
if (strcmp(input, suche) == 0) {
for (x = 0; x < 4; x++) {
fgets(output, max, file);
printf("%s", output);
}
}
}
fclose(file);
return 0;
}
这是要搜索文本部分的文件:
Hello
coolcool
horse
miein
Hello
cookiecookie
horse
lol
This
testetst
door
nicht
Thoes
breadbread
read
ja
【问题讨论】:
-
您是在调试器中调试程序还是在其中放入了一些 printf 语句?
-
Why is “while ( !feof (file) )” always wrong? - 在你的代码中这是特别错误的,因为你有嵌套循环
fgets根本没有检查EOF -
次要:
fgets(input, max, stdin);的大小比它可以使用的小 1。使用fgets(input, max +1, stdin);甚至更好:fgets(input, sizeof input, stdin);