How can I count all the vowels in a string using C++?

0
9
Asked By CodeWhiz123 On

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

Answered By TechGuru42 On

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!

StringMaster96 -

Exactly! And make sure to check both uppercase and lowercase if you're dealing with mixed cases.

Answered By LoopLover99 On

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!

CodeWhiz123 -

Thanks, I’ll try adding that to my code!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.