I'm trying to compare two characters (my search character, and the characters in an input string) to see how many of my search characters are present in the given string. But, all I am getting for the count is 0, no matter what I input.
Below is my code for reference:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int length = 0;
char ch;
char search;
int count = 0;
length = str.length();
cin >> search;
cin >> str;
for (int i = 0; i < length; i++) {
//current character
ch = str[i];
//cout << ch << " ";
if (ch == search) {
count += 1;
}
}
cout << count << " " << search << "'s" << endl;
return 0;
}
I've tried both ch.compare(search)
and (ch == search)
, as seen in my code. Both just result in me getting 0 for count
. I've also flipped ch
and search
, and tried to set both search
and ch
to ' '
, but again none of it did anything. Example of one of the tests I've tried is below.
How many
e
's are in the string"Geek"
.
I don't know what I am doing wrong, as all I'm getting as the output is 0 for count
.
For example:
Input: "Geek"
Wanted Output: 2 e's
What I'm getting: 0 e's
I'm using CLion for my IDE, with my Language Standard set at C++23.