Grupo
Funciones en C++
Ojetivo
1. Define una función que tome una cadena como entrada.
2. Recorre cada carácter de la cadena.
3. Comprueba si el carácter es una vocal (minúscula o mayúscula).
4. Cuenta el número de vocales y devuelve o muestra el resultado.
Crea una función que cuente el número de vocales en una cadena.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library for input and output
#include <string> // Include the string library to work with strings
using namespace std; // Use the standard namespace
// Function to count the number of vowels in a string
int countVowels(string text) {
int count = 0; // Initialize the vowel count to 0
// Loop through each character in the string
for (char ch : text) {
// Convert character to lowercase for easier comparison
ch = tolower(ch);
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++; // Increment the counter if a vowel is found
}
}
return count; // Return the total number of vowels
}
// Main function
int main() {
string input;
// Prompt the user to enter a string
cout << "Enter a string: ";
getline(cin, input); // Read the full line of text
// Call the function and display the number of vowels
int vowels = countVowels(input);
cout << "Number of vowels in the string: " << vowels << endl;
return 0; // End of program
}
Salida
Enter a string: Hello World
Number of vowels in the string: 3
Comparte este ejercicio C++