c++file-handlingcountingfind-occurrences

In my project i have to create a program that reads a file and counts the number of occurrences of a specific word


So far it reads the file and counts each word in the file, but i want it to count just the word "Ball". I'm wondering how can I do that. Here's what's in the text file and the code:

Programming.txt

Ball, Ball, Cat, Dog, Ball,
#include <iostream>
#include <fstream>
#include <string> 
#include <sstream>
using namespace std;

int main()
{
    
    ifstream file("Programming.txt");

    if(file.is_open())
    {
        string line;
        int wordcount = 0;
        
        while(getline(file, line))
        {
            stringstream ss(line);
            string word = "Ball";
        
            while(ss >> word)
            {
                wordcount++;
            }
        }

        file.close();
        cout << "Ball occurred " << wordcount << " times";
    }
    else
    {
        cerr << "File is closed!";
    }   
}

The output i get is "Ball occurred 5 times"

I tried giving each "word", "line" and "ss" variable the value "Ball":

word = "Ball"
line = "Ball"
stringstream ss = "Ball";
ss(line);"

i also tried using a for loop to count each occurrence of Ball using the word variable:

word = "Ball"
for(int i = 0; i <= word; i++)
{  
cout << i;
}

I expected both of these to count only the word "Ball"

all failed unfortunately


Solution

  • You need to compare the value of word after you read it from the file, eg:

    string word;
    
    while (ss >> word)
    {
        if (word == "Ball")
            wordcount++;
    }
    

    However, this alone will not work in your case, because the words in your file are delimited by , which you are not accounting for. operator>> only cares about whitespace, so word will end up being "Ball," instead of "Ball".

    Try something more like this instead to ignore the , characters:

    #include <iomanip> // needed for std::ws
    
    ... 
    
    string word;
    
    while (getline(ss >> ws, word, ','))
    {
        if (word == "Ball") 
            wordcount++;
    }
    

    Live Demo