Im working on a code that asks the user to enter a line of text and a word they would like the code to count the number of occurrences for. However, say if I input the line "The fox is running. The rabbit is running." and ask the program to count the number of occurrences for the word "the", it outputs 2. Correct. But if I input the line "thethethethe" and ask the program to count for "the" again then it outputs 0. I don't understand why it counts the occurrence for "the" in the first example correctly but not the second. Can someone take a look and see what Im doing wrong?
// This program prompts the user to enter a line of text and the
// word he/she wants to know the number of occurrence for.
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
usingnamespace std;
int main()
{
string line_of_text;
string word;
// Prompt user to enter line of text
cout << "Enter your line of text." << endl;
getline(cin, line_of_text);
// Prompt user to enter word for occurence
cout << "What word do you want to count the number of occurence for?" << endl;
getline(cin, word);
// Find occurence
for (string::size_type i = 0; i < word.length(); i++)
{
line_of_text[i] = tolower(line_of_text[i]);
}
stringstream ss(line_of_text);
int count = 0;
while (ss >> line_of_text)
{
if (line_of_text == word)
{
count++;
}
}
cout << "The word " << "'" << word << "'" << " occurs " << count << " times." << endl;
return 0;
}
// This program prompts the user to enter a line of text and the
// word he/she wants to know the number of occurrence for.
#include <iostream>
//#include <string>
//#include <sstream>
//#include <cctype>
usingnamespace std;
int main()
{
string text="";
string word="";
int notFound=0; // flag if word found
int match=0; // count times word found
// Prompt user to enter line of text
cout << "Enter your line of text.: ";
getline(cin,text);
cout << endl;
// Prompt user to enter word for occurence
cout << "What word do you want to count the number of occurence for? ";
getline(cin,word);
// Find occurence
if (text.length()>= word.length())
{
for (unsignedint i = 0; i < text.length()-word.length()+1; i++)
{
notFound = 0;
for (unsignedint p=0; p < word.length();p++)
{
if (text[i+p] != word[p])
{
notFound = 1;
}
}
if (notFound == 0)
match = match + 1;
}
}
cout << "number of times '" << word << "' found in '" << text << "' = " << match << endl;
return 0;
}
Is counting "the" in "thethethethe" esp. useful? The spaces allow us to identify where the words are. If you count "the" in the string "thereisatheorythatthesetsthetheme" for the word "the" then I'd expect 2 not 5 (there, theory, and theme begin with "the" but aren't that word.)