I have written this code to enter a string and then count the number of a user input character. For example you enter a string and then it ask to input a chacater to count the number of occurances that chacater appears in the string. My code only returns a value of 1.
the code;
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
int i = 0, letter;
int cnt = 0;
cout << "Enter String: \n";
getline(cin, message, '\n');
cout << "\nEnter a letter to count in he string: " << endl;
cin >> letter;
unsigned pos = message.find(letter, 0);
while ( pos != string::npos ) {
cnt++;
pos = message.find(letter, pos);
}
cout << "character occurred " << cnt << " times.\n" << endl;
return 0;
}
Tags: