I am writing a function that returns the number of vowels for a given string, here is the code:
int isVowel(string sequence)
{
int numberOfVowels = 0; //Initialize number of vowels to zero
string vowels = "aeiouAEIOU"; //Possible vowels, including capitals
for (int i = 0; i <= sequence.length(); i++)
{
for (int j = 0; j <= vowels.length(); j++)
{
if (sequence[i] == vowels[j])
{
numberOfVowels += 1;
}
}
}
return numberOfVowels;
}
This returns answers that are off by one. For example, input of "a" returns 2, input of "aa" returns 3, etc.
i <= sequence.length()
<=
is almost never correct in any for loop since C++ uses 0-based indices. Instead, you should do
i < sequence.length()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.