-1

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.

2 Answers2

2

Your code has a small by crucial error in it. You are passing the strings to your RemovePunct and ToLowercase methods by value, rather then by reference, so you are changing a copy of the string, rather than the string itself.

You should change your method definitions as following:

void ToLowercase(string & word) {

and

void RemovePunct(string & word) {

Read some more about it here

Edited:

Since you are now passing the string as an input/output variable by reference, there is also no point in returning any value from the method, so the return type is now void, and you should omit the return word; from both methods.

Daniel Trugman
  • 8,186
  • 20
  • 41
0

Your Functions RemovePunct and ToLowercase Returns the modified string but you never take it.

You can either change the code inside the loop to

word = RemovePunct(word);
word = ToLowercase(word);

or make the functions as :

void RemovePunct (std::string& wo );

and

void ToLowercase (std::string& wo);

and then remove the return statements in the two functions as the other answer has said.

WARhead
  • 643
  • 5
  • 17