I have a program that reads in a file, goes through line by line, and breaks up the line word by word. My problem is, I am about to store each word in a array but I need to use strcmp
function to verify the word doesnt already exist. Anyways below is my code and my question is, why is my program printing out 1
so many times? I was expecting it to only print it out twice because this
occurs twice in my text file.
while (fgets(line, sizeof(line), fi) != NULL) { // looping through each line
line_count += 1;
for (j = 0; j < sizeof(line); j++) { // convert all words to lowercase
line[j] = tolower(line[j]);
}
result = strtok(line, delimiters);
while (result != NULL) {
word_count += 1;
if (strcmp(result, "this")) {
printf("1\n");
}
result = strtok(NULL, delimiters); // get the next token
}
}
Below is my text file:
This is the first test.
This is the second test.
strcmp()
returns 0
if the string matches. You're checking for a truthy value. You really want strcmp(result, "this") == 0
.
You will also need to make the match case insensitive, which is usually called stricmp()
.