I mostly have this program completed but there is one problem i cannot figure out, this programs asks the user to search for a word, next the user is asked which file to open, then the program is to search the .txt file for any traces for the word that has been searched, whether it its upper case or lower case.
However in my example with the supplied .txt file, i try to search for the word "Peter" i get the following
Code:
Please enter the word you would like to search for.
peter
Please enter the filename to read from.
words.txt
Word found: THis is a sentence
Line: 1
Word found: peter how many words does it contain
Line: 2
Kinda weird if you ask me lol.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringtolower(char * str);
int main()
{
char searchword[100];
char filename[100];
char word[100];
char originalword[100];
printf("Please enter the word you would like to search for.\n");
scanf("%s", searchword);
stringtolower(searchword);
printf("Please enter the filename to read from.\n");
scanf("%s", filename);
FILE * fptr;
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Error file was not opened correctly\n");
exit(1);
}
else
{
int lineNumber = 1;
while(fgets(word, 100, fptr) != NULL)
{
strcpy(originalword, word);
stringtolower(word);
if (strcmp(word, searchword) ==1)
{
printf("Word found: %s Line: %d\n\n", originalword, lineNumber);
}
lineNumber++;
}
}
fclose(fptr);
return 0;
}
void stringtolower(char * str)
{
int i;
for (i=0; i < strlen(str); i++)
{
if (str[i] >= 'A' && str[i] <='Z')
{
str[i] = str[i] + ('a' - 'A');
}
}
}