用C语言写一个代码,要求输入一个单词,在文件中找出所有出现该单词的句子及单词出现的位置,并且统计该单词出现的次数
时间: 2024-02-03 10:15:02 浏览: 32
以下是一个可以实现你要求的C语言代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_SENTENCE_LENGTH 1000
#define MAX_WORD_LENGTH 50
int main()
{
char filename[100];
char word[MAX_WORD_LENGTH];
char sentence[MAX_SENTENCE_LENGTH];
char *pos;
int lineno = 0, count = 0;
printf("Enter filename: ");
scanf("%s", filename);
printf("Enter word to search: ");
scanf("%s", word);
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Failed to open file %s\n", filename);
return 1;
}
while (fgets(sentence, MAX_SENTENCE_LENGTH, fp) != NULL)
{
lineno++;
pos = strstr(sentence, word);
while (pos != NULL)
{
count++;
printf("Line %d: %s", lineno, sentence);
printf("Word '%s' found at position %d\n", word, pos - sentence + 1);
pos = strstr(pos + 1, word);
}
}
printf("The word '%s' appears %d times in the file.\n", word, count);
fclose(fp);
return 0;
}
```
这个程序会要求用户输入一个文件名和一个单词,然后在文件中查找出现该单词的句子及单词出现的位置,并且统计该单词出现的次数。程序会逐行读取文件内容,然后使用 `strstr()` 函数查找单词出现的位置,如果找到了就打印出该句子及单词出现的位置,并继续在该句子中查找单词出现的位置直到找不到为止。最后程序会打印出单词在文件中出现的次数。