211k views
0 votes
Write a C++ program that prompts the user to enter a string of text, and then counts the number of vowels (a, e, i, o, u) in the string. The program should then print the output as follows if the user enters the "Hello, World!" string: (10)

User Old Newbie
by
7.0k points

1 Answer

7 votes

Final answer:

To count the number of vowels in a string using a C++ program, you can iterate through each character of the string and use a switch statement to check if each character is a vowel. If it is, increment a counter variable. Finally, print the value of the counter to display the number of vowels in the string.

Step-by-step explanation:

To write a C++ program that counts the number of vowels in a string entered by the user, you can use a loop to iterate through each character in the input string. Inside the loop, you can use a switch statement to check if each character is a vowel (a, e, i, o, u). If it is, you can increment a counter variable. Finally, you can print the value of the counter to display the number of vowels in the input string.

Here's an example implementation:

#include <iostream>
#include <cctype>

int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);

int vowelCount = 0;

for (char c : input) {
switch (std::tolower(c)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
break;
default:
break;
}
}

std::cout << "Number of vowels: " << vowelCount << std::endl;

return 0;
}

User Ralokt
by
7.1k points