I'm working on a C++ function to count how many vowels are present in a given string. The problem I'm facing is that my current code only increments the count when it finds a single vowel. When I try to input a string with multiple vowels, it just resets back to zero. Here's the code I have so far. Can anyone suggest how to fix this?
```cpp
using namespace std;
int getCount(const string& inputStr){
int num_vowels = 0;
// your code here
if (inputStr == "a" || inputStr == "e" || inputStr == "i" || inputStr == "o" || inputStr == "u") {
num_vowels++;
}
return num_vowels;
}
```
2 Answers
It looks like you're trying to check the whole string at once instead of each character individually. You need to loop through the string and check each character. Here's a suggestion:
```cpp
int getCount(const string& inputStr) {
int num_vowels = 0;
for (char c : inputStr) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
num_vowels++;
}
}
return num_vowels;
}
```
This way, you increment the count each time you find a vowel in the string!
Another approach is to use a `std::string::find_first_of()` method to find vowels more compactly, like:
```cpp
int getCount(const string& inputStr) {
int num_vowels = 0;
for (char c : inputStr) {
if ("aeiouAEIOU".find(c) != string::npos) {
num_vowels++;
}
}
return num_vowels;
}
```
This way, your code also handles uppercase vowels!
Thanks, I’ll try adding that to my code!
Exactly! And make sure to check both uppercase and lowercase if you're dealing with mixed cases.