Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading