0

For some reason, when I include the first for loop, the second for loop doesn't run and 0 keeps getting printed out. When I get rid of it, the program runs as expected (e.g., "aaaaa iiiii ooooo" gives me 15).

Version that works:

#include <iostream>
#include <string>
using namespace std;

int numOfVowels;
string phrase;

int main(){
getline(cin, phrase);
for (int j = 0; j < phrase.size(); j++)
{
    if(phrase[j]=='a' || phrase[j]=='e' || phrase[j]=='i' || phrase[j]=='o' || phrase[j]=='u')
        numOfVowels++;
}
cout << numOfVowels;
}

Version that doesn't work:

#include <iostream>
#include <string>
using namespace std;

int main() {

    int numOfVowels, loop;
    string phrase;
    cin >> loop;

    for(int i = 0; i < loop; i++) //removing this for loop makes the program work
    {
        getline(cin, phrase);
        for (int j = 0; j < phrase.size(); j++)
        {
            if(phrase[j]=='a' || phrase[j]=='e' || phrase[j]=='i' || phrase[j]=='o' || phrase[j]=='u'|| phrase[j]=='y')
                numOfVowels++;
        }
        cout << numOfVowels;
    }
}

Can someone tell me what I'm doing wrong here? Thank you

Ken White
  • 123,280
  • 14
  • 225
  • 444
kenavuen
  • 51
  • 1
  • 6
  • Can you show the 2 versions of the code, and identify which is which? – Scott Hunter Jun 20 '21 at 22:18
  • 4
    `numOfVowels` is uninitialized. – 273K Jun 20 '21 at 22:18
  • You also have this problem: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Blastfurnace Jun 20 '21 at 22:21
  • @ScottHunter I edited my post to include the version that works and the version that doesn't work – kenavuen Jun 20 '21 at 22:29
  • Thank you both @S.M. and Blastfurnace, after initializing numOfVowels to 0 and using cin instead of getline(), my program works – kenavuen Jun 20 '21 at 22:39

0 Answers0