Reputation: 23
I'm told to ask the user for a string ( a sentence). Then the user is asked to input another string to search in string 1 (the sentence). The program has to count the number of times the second string shows up in the first string. I'm not getting any errors but it's is not counting the letters. This is the result i get:
Enter a sentence:i love to eat soup
Enter string to search: ou
There are 0 of the string ou in the first string you provided.
Can someone please tell me what i'm doing wrong? I'm a beginner at c++ so i'm having some trouble understanding.
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence;
string search;
int count = 0;
cout<<"Enter a sentence:";
getline (cin, sentence);
cout<<"Enter string to search:";
getline (cin, search);
cout << "There are " << count << " of the string " << search << " in the first string you provided." <<"\n";
for (int i=0; i < sentence.size(); ++i)
{
if (sentence == search)
count++;
}
return count;
}
Upvotes: 0
Views: 177
Reputation: 126412
You should modify your loop so that it really searches for substrings and count their occurrences:
string::size_type pos = sentence.find(search);
while (pos != string::npos)
{
pos = sentence.find(search, pos + search.size());
count++;
}
Also, you most likely want to move this line after the point where you actually compute the value of count
:
cout << "There are " << count << ...
Otherwise, it will obviously output the value to which count
was initialized originally (i.e. 0
).
Upvotes: 0
Reputation: 54554
Two issues:
count
before you calculate it.std::string
to find an appropriate way to search for substrings. However, you are on the right track.Upvotes: 2
Reputation: 578
looks like you should put the cout statement in the end of this method. Because in your code, count is always 0 when you output it
Upvotes: 0
Reputation: 649
You have your cout print line after the loop where you search for the string and set the count. Move it below that loop.
Upvotes: 0
Reputation: 385108
Well, you're trying to output the results before calculating them.
Also, ==
is for exact matches, not substring searches.
Upvotes: 0