Tiphe Tiphe - 3 months ago 10
C++ Question

Asking to write a sentence in a loop to count vowels, won't ask again even when the loop goes on

Title might be a bit confusing, I tried to be as specific as I could

Hi, total c++ beginner here, trying to make work a simple program that should tell me how many vowels a sentence contains. Problem here is the loop is not asking me to write a sentence like it should when it continues after the first iteration.

So basically here's my code :

#include <iostream>
using namespace std;
int main(){
int i, nb_vowels, cont=1;
char sentence[100];

while(cont!=0){
cout << "Enter a sentence : ";

while ((sentence[i] = getchar()) != '\n') {
i++;
if(sentence[i]=='a' || sentence[i]=='e'|| sentence[i]=='i' || sentence[i]=='o' || sentence[i]=='u'){
nb_vowels++;
}
}
sentence[i] = '\0';

cout << "Number of vowels : " << nb_vowels <<endl;

cout << "1 to continue or 0 to stop : ";
cin >> cont;
}
}


Here's an example of how it goes when I execute it :

Enter a sentence : hello i am learning c++
Number of vowels : 1 //that part is still not working btw, but i want to know how to fix the loop problem first
1 to continue or 0 to stop : 1
Enter a sentence : Number of vowels : 1 //i cant write anything here, it just pops like that
1 to continue or 0 to stop :


Here's how it should go :

Enter a sentence : hello i am learning c++
Number of vowels : 6
1 to continue or 0 to stop : 1
Enter a sentence : wooo it works
Number of vowels : 1
1 to continue or 0 to stop : 0


I'm kind of lost right now as I know so little about C++ (only started a few days ago), any help would be greatly appreciated!

Answer

First of all, i and nb_vowels are not initialized to anything, initialize properly like: int nb_vowels = 0, i = 0;

Secondly, why don't you use cin.getline(sentence, 100); to input a sentence, why looping yourself to do this task?

And if you use cin.getline, you'd have to add an cin.ignore(); after your input of cin >> cont;

Here's the code you can use to perform this task:

int cont = 1;
int nb_vowels = 0;
char sentence[100];
while (cont != 0){
    cout << "Enter a sentence: ";
    cin.getline(sentence, 100);
    int sentenceSize = strlen(sentence);
    for (int i = 0; i < sentenceSize; i++){
        if (sentence[i] == 'a' || sentence[i] == 'e'|| sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
            nb_vowels++;
    }
    cout << "No. of Vowels: " << nb_vowels << endl;
    cout << "1 to continue or 0 to stop : ";
    cin >> cont;
    cin.ignore();
}

Better yet, you should use std::string instead of char array. Read about the string, it's pretty simple, if you'd have any problem regarding that, first search about that problem, and then come with some real problem.