Reputation: 1
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
Upvotes: -3
Views: 82
Reputation: 1
To count only the word "Ball" in your file, you need to modify your program to specifically check if each word read from the file matches the word "Ball" (considering case sensitivity and punctuation). You should compare each word from the stream with the string "Ball", and only increment the counter if it matches exactly.
Here is an updated version of your code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream file("Programming.txt");
if(file.is_open())
{
string line;
int wordcount = 0;
while(getline(file, line))
{
// Replace commas, periods, etc., with spaces to handle punctuation
for (char& c : line)
{
if (ispunct(c)) // Check if the character is punctuation
{
c = ' '; // Replace punctuation with space
}
}
stringstream ss(line);
string word;
while(ss >> word)
{
// Convert to lowercase for case-insensitive comparison
transform(word.begin(), word.end(), word.begin(), ::tolower);
if (word == "ball") // Case-insensitive comparison
{
wordcount++;
}
}
}
file.close();
cout << "Ball occurred " << wordcount << " times" << endl;
}
else
{
cerr << "File is closed!" << endl;
}
}
Upvotes: 0
Reputation: 597896
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++;
}
Upvotes: 2