In your example, you fail to ensure the character before the one being checked is whitespace. Doing that and your approach will work. You don't want to know how many characters there are that match charr
, you want to know how many words start with charr
. To calculate that from the entire std::string
, you need to check that the previous character is whitespace.
You can easily check whether the previous character is whitespace by including cctype
and using the isspace()
macro.
Additionally, you must validate EVERY user-input. The user may generate a manual EOF
to cancel input which is a valid user-action. (Ctrl + d or Ctrl + z on windows).
A short example using your read with getline()
, removing using namespace std;
and choosing a new name for your string (line
instead of main
) would be:
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string line {};
char charr = 0;
int count = 0, last = 0;
std::cout << "Enter the main string : ";
/* validate read and line not empty */
if (!getline(std::cin, line) || line.size() == 0) {
return 0;
}
std::cout << "Enter a character: ";
if (!(std::cin >> charr)) { /* validate read */
return 0;
}
if (line[0] == charr) { /* check 1st char */
count++; /* increment on match */
}
last = line[0]; /* set last char seen */
for (size_t i = 1; i < line.size(); i++) { /* loop 1 to end */
/* last is space and current is charr */
if (isspace(last) && line[i] == charr) {
count++; /* increment count */
}
last = line[i]; /* set last char seen */
}
std::cout << count << '\n'; /* output results */
}
(note: while using namespace std;
may be fine and convenient for small example programs, see: Why is “using namespace std;” considered bad practice?)
Example Use/Output
$ ./bin/startswith
Enter the main string : my dog has fleas and my cat has none
Enter a character: h
2
Or
$ ./bin/startswith
Enter the main string : my dog has fleas and my cat has none
Enter a character: n
1