I'm attempting to create a program that reads a file and asks for a word. It then outputs the amount of times it is used in the file.
This is the what is in the file it is reading:
This file contains many words. Many, many words. Well, maybe it is not that many after all. So, just how many is MANY?
Word Occurrences:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;
string RemovePunct(string word) {
char exc = '!';
char comma = ',';
char period = '.';
char question = '?';
for (int i = 0; i < word.length(); i++) {
if (word[i] == exc) {
word.pop_back();
}
else if (word[i] == comma) {
word.pop_back();
}
else if (word[i] == period) {
word.pop_back();
}
else if (word[i] == question) {
word.pop_back();
}
}
return word;
}
string ToLowercase(string word) {
transform(word.begin(), word.end(), word.begin(), tolower);
return word;
}
int main() {
string wo;
cin >> wo;
transform(wo.begin(), wo.end(), wo.begin(), tolower);
ifstream in("words.txt");
int wordcount = 0;
string word;
while (in >> word) {
RemovePunct(word);
ToLowercase(word);
cout << word << endl; // used to check if 'word' has changed
if (word == wo) {
++wordcount;
}
}
cout << wordcount << endl;
// outputs 4
// should output 6
}
As you can see it doesn't account for every 'many' in the file. I attempted to take the punctuation and make the characters lowercase to account for each 'many' but the changed word does not return into my main function. So I'm looking for help on where I might've gone wrong.