-3

I have a text file that I am supposed to open, scan, and count the amount of times a particular word or string occurs in the text file ("#email" to be exact). I have been able to count the number of words that occurs in the whole text file but not count the number of times a particular word or string occurs. Can anyone give me any advice?

int count = 0;
std::string word;
std::string strg1("#email");
std::ifstream fin;

fin.open(filename + "-inbox.txt", std::ios::in);

while (fin >> word)
{

    if (word == strg1)
    {
        count++;
    }
}

fin.close();
return count;

1 Answers1

5

Your code seems fine to me (and compier as well). But be aware of the fact, that istream's overloaded operator>> for std::string reads "words", which is (by means of C++), sequence of chars divided by whitespace. Your example reads such words. So in sentence

There are many #email words in this sentence (#email is located in here also), but #email, for some reason, is not here.

has only one occurence of #email (and one (#email and one #email,).

Zereges
  • 5,139
  • 1
  • 25
  • 49
  • But it is easy to modify the local so that punctuation is treated as space: [How to tokenzie (words) classifying punctuation as space](http://stackoverflow.com/a/6154217/14065) – Martin York Dec 05 '15 at 00:30