I have a simply task that I wish to do here is the workflow
- User inputs a string which he/she wishes to search exits in a text file
- If string is found, code then prints all the lines in a text file where that string exists.
- Code terminates/function ends.
Now I managed to get file reading working and all, but the issue happens when I combine user input.
For example, when the user inputs "sushi" it does not print out the lines of string in the text file where the word "sushi" exists.
But if I pass the term manually, it works fine (i.e strstr(lineOfText,"sushi));
Here is my code, what could the issue be
int main() {
word_search();
return 0;
}
int word_search() {
FILE *textFile;
char line[MAX_LINE_LENGTH];
textFile = fopen("PATH TO TEXT FILE", "r");
if (textFile == NULL) {
return 1;
}
printf("Please input word to search:");
char userInput[] = "";
fgets(userInput, 250, stdin);
while (fgets(line, MAX_LINE_LENGTH, textFile)) {
if (strstr(line, userInput) != NULL) {
printf("%s", line);
}
}
fclose(textFile);
return 0;
}
Contents of file
1 Wallaby Way Fenwick
1 Sushi Way Fenwick
1 Wallaby Sushi Way Fenwick
1 Alexandria Way Fenwick
1 Alexandira Sushi Ashfield Way Fenwick
char. You need to study how arrays work before using strings. Here's a newbie FAQ: Common string handling pitfalls in C programmingfgets(), reading fromstdinleaves the'\n'on the end of the string. You won't find "Way", either, but will have success with "Fenwick" from the keyboard because that will be "Fenwick\n" in the buffer...line[ strcspn( line, "\n" ) ] = '\0';will fix your problem... (PS: That's a very peculiar filename.) (PPS: "sushi" will not match "Sushi"... Details matter...)