inundar
inundar

Reputation: 21

Finding vowels in user input array

// I am new to c++ and I don't understand all of the syntax rules and how certain things like pointers behave. I want to know about how to make a program to find the vowels in an input array, no vectors suggestions please. I know I may be doing this the hard way but I want to know the why and how of things better.

#include<iostream>
using namespace std;

int main()
{
    int sum = 0;
    int n;
    char vowels[6] = {'a', 'e', 'i', 'o', 'u', 'y'};
    char *word = NULL;
    cout << "Enter word" << endl;
    cin >> n;

    for(int i=0; i < n; i++)
    {
        for(int j=0; j < 6; j++) 
            if(word[i] == vowels[j])
            {
                sum++;
            } 
        cout << sum;
    } 
    delete [] word;
    word = NULL;

    return 0;
}

Upvotes: 1

Views: 3280

Answers (3)

Mathews Sunny
Mathews Sunny

Reputation: 1642

You need to take care of few things in your program segment.

  1. You need to create a char array (e.g word[20]) for reading the string.
  2. You need to read line into the char array and not to int (cin >> n;).
  3. You cant read in a string using 'cin'.
  4. you need to print sum (no. of vowels) outside loop.

    #include<iostream>
    #include<string.h>
    using namespace std;
    
    int main()
    {
        int sum = 0;
        int n;
        char vowels[6] = {'a', 'e', 'i', 'o', 'u', 'y'};
        char word[20] = NULL;
        cout << "Enter word" << endl;
        while (getline(cin, word)) //read line of text including white space until enter key is pressed
        {
    
        }
        n=strlen(word);      //get the length of the input string  
        for(int i=0; i < n; i++)
        {
            for(int j=0; j < 6; j++) 
                if(word[i] == vowels[j])
                {
                    sum++;
                }      
        } 
        cout << sum;   //Print total number of vowles
        delete [] word;
        word = NULL;
    
        return 0;
    }
    

    This would generate desired output.

Upvotes: 1

BusyProgrammer
BusyProgrammer

Reputation: 2781

Couple of mistakes in your code:

Firstly, cin >> word does not take a word as input, it only takes a number. This is because word is of type int.

Also, you need to print sum outside the for loop so that it is not continuously printed.

Upvotes: 0

user7876696
user7876696

Reputation: 11

You need to set the inputted value into word and you print the sum after each letter because you're printing inside of the loop that goes through the word.

Upvotes: 1

Related Questions