This is actually my homework and the question states:
“The program should determine how many times the character is
contained in the string. (Hint: Search the string by using the
find(str,ƒind) method. This method should be used in a loop that
starts the index value at 0 and then changes the index value to 1 past
the index of where the char was last found.)”
This is what I’ve came up with but all it does is count how many character there is in the string. New to C++ so I hope you guys can be patient with me.
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
char c;
size_t contain;
int count = 0;
cout << "Enter a string : ";
getline(cin, s);
cout <<"Enter a char : ";
cin >> c;
for(int i = 0; i < s.length(); i++)
{
contain = s.find(c, i);
if (contain =! string::npos )
{
count++;
}
}
cout << count <<endl;
return 0;
}
I think @parapura’s code looks nice’er like this:
and it solves the problem nicely 😉