I must make a program taking into account that a string behaves like an array make.
Lose a text string to the user and:
indicate how many words it has
Indicate how many times each vowel appears in the entered string, if there is none, it should be indicated as 0.
The part of how many words does it have, works correctly for me. The problem is in the second point, when counting the number of vowels, numbers appear greater than those entered.
#include <iostream>
using namespace std;
int ContarPalabras ( char [] );
int main (){
char cadena [400];
int vocal_a=0,vocal_e=0,vocal_i=0,vocal_o=0,vocal_u=0;
cout<<"Ingrese una frase: "<<endl;
cin.getline(cadena, 400);
cout<<"La cadena de texto ingresada contiene " <<ContarPalabras(cadena)<<" palabras."<<endl;
// segundo punto
for (int i=0; i<400; i++){
switch(cadena[i]){
case 'a': vocal_a++;break;
case 'e': vocal_e++;break;
case 'i': vocal_i++;break;
case 'o': vocal_o++;break;
case 'u': vocal_u++;break;
}
}
cout<<"Vocal a: "<<vocal_a<<endl;
cout<<"Vocal e: "<<vocal_e<<endl;
cout<<"Vocal i: "<<vocal_i<<endl;
cout<<"Vocal o: "<<vocal_o<<endl;
cout<<"Vocal u: "<<vocal_u<<endl;
return 0;
}
int ContarPalabras (char cad [])
{
int palabras = 0;
for (int i=1; cad[i]!='\0'; i++){
if (cad [i-1]== ' '&&isalpha(cad[i]))
palabras++;
}
if (isalpha(cad[0])) palabras++;
return palabras;
}
This is how the problem looks graphically
The problem you have is that you are going through the 400 positions of the array like crazy
Here you should only loop through the length of the string entered by the user, as the rest of the array will contain garbage values.