我正在尝试编写一个单词搜索代码,该代码从100x201 char文本文件中获取输入,并逐行搜索文件中的关键字,如果在该行中找到该关键字,则会打印该行,行号,以及找到单词的次数。这段代码可以正确地找到每一行中的单词,但是即使下一行没有出现,它也会打印出下一行也包含该单词。在我的输出中,应该显示“ MAIN”仅在第163和187行中总共发现了4次,而不是163,164、178,188总共出现了7次。链接显示图片,左边是我的输入文件的一部分,右边是我的当前输出。
https://www.tumblr.com/blog/jnimnim
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void my_strcpy(char In[], char Out[], int L) { //copies ln_string[i] to tempword with "length" amount of characters
int i;
for (i = 0; i < L; i++)
{
Out[i] = In[i];
}
Out[L] = '\0';
return;
}
int search_current_line(char Line_str[], char word[]) { //function to search one line
int i,length,count;
count = 0;
length = strlen(word); //find length of desired word
char tempword[15]; //declare a temp string that we can use strncmp with word
for (i = 0; i <= 99; i++) { //one iteration for each character in line
my_strcpy(&Line_str[i], tempword, length);
if (strncmp(word, tempword, length) == 0) {//check if word=tempword
count = count + 1; //if true increment counter
}
}
return count;
}
int main() {
char YorN ='Y';
while (YorN == 'Y') {
int line = 0; //initialize variables at beginning of loop
int totalcount = 0;
char line_str[100];
char word[15];
FILE *inp;
inp = fopen("DataFile.txt", "r"); //open input file
printf("Enter word to search for (all caps):"); //prompt user for word
scanf("%s", &word);
printf("\n\n");
while (!feof(inp)) { //while not end of file
fgets(line_str, 100, inp); //read line into string
line = line + 1; //increment line count
if (search_current_line(line_str, word) >= 1)
{
printf("%s was found %d times on line %d\n", word, search_current_line(line_str, word), line); //print statements if word was found in line
printf("The line is:\n%s\n\n", line_str);
totalcount = totalcount + search_current_line(line_str, word); //increment totalcount by searchline function because it returns count
}
}
if (totalcount > 0) {
printf("%s was found a total of %d times in the puzzle.\n\n", word, totalcount);//print at end if word was found in puzzle
}
else {
printf("%s was not found in the puzzle.\n\n", word);//print if word wasn't found
}
printf("Would you like to look for another word? (Y or N):"); //ask user to continue
scanf(" %c", &YorN);
}
printf("Goodbye.\n");
return 0;
}