My assignment is as follows:
- Add a naughty word to the list
- Show all naughty words in the list
- Input sentence needing to be censored
I need to save naughty words in a file and compare if the user input contains a bad word, so i can censor it with stars. My problem is I can't seem to figure out why my method of comparing each word in the sentence to the "naughtyList.txt" isn't working. My strcmp code in OptionThree() doesn't work for a full sentence.
Here are my 3 functions:
void OptionOne() {
char word[20];
//"a" for continue writing in the same file, and not overwrite it
FILE *list = fopen("naughtyList.txt", "a");
printf("Enter new naughty word: ");
scanf("%s", &word);
fputs(word, list);
fputs("\n", list);
fclose(list);
}
void OptionTwo() {
FILE *list = fopen("naughtyList.txt", "r");
char word[20];
if(list == NULL) {
printf("Naughty words list does not exist, add some word in the list first\n");
}else {
printf("All naughty words in the list: \n");
while(fgets(word, sizeof(word), list)) {
printf("%s", word);
}
}
fclose(list);
}
void OptionThree() {
FILE *list = fopen("naughtyList.txt", "r");
char word[20];
char input[100];
char eachWord[20][20];
char *pointer;
int i = 0;
int count = 0;
printf("Input your sentence: ");
fflush(stdin);
fgets(input, sizeof(input), stdin);
//solution for getting each word in a string using strtok
for(pointer = strtok(input, " "); pointer != NULL; pointer = strtok(NULL, " ")) {
strcpy(eachWord[i], pointer);
i++;
count++;
}
for(i = 0; i < count; i++) {
while(fgets(word, sizeof(word), list)) {
word[strcspn(word, "\n")] = 0; // remove tralling \n at the end of naughty word list when scaning file
if(strcmp(eachWord[i], word) == 0) {
printf("PING\n");
}
}
}
fclose(list);
}