Program to count all vowels individually

Hi guys,
I need help writing a program that outputs the number of vowels in a string using a while loop, and it will output
number of a's
number of e's
number of i's
number of o's
number of u's

Thanks guys.
Zero, create a variable to store the current amount.
First, iterate through each character from a string.
Second, check whether the current character is either a,e,o,i, or u.
Third, if it is equal to any of those, increment the current amount variable and continue the loop.
Fourth, output the amount :)
I did not test the code. It is just an idea how the program could be written if you do not know yet std::map. Otherwise it is better to use std::map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>

const char vowels[] = "aeiou";
const size_t VOWELS_NUM = sizeof( vowels ) - 1;

int IsVowel( char c )
{
   c = std::tolower( c );

   const char *p = std::strchr( vowels, c );

   return ( ( p ) ? p - vowels + 1 : 0 );
}

int main()
{
   std::string s( "This is just a test" );
   int count[VOWELS_NUM] = {};

   std::cout << s << std::endl;

   for ( std::string::size_type i = 0; i < s.size(); i++ )
   {
      int pos = IsVowel( s[i] );
      if ( pos ) count[--pos]++;
   }

   for ( size_t i = 0; i < VOWELS_NUM; i++ ) std::cout << count[i] << ' ';
   std::cout << std::endl;

   return ( 0 );
}      
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cctype>

int main(void) {
    int count[5] = { 0, 0, 0, 0, 0 };
    const char *vowels = "aeiou";
    const char *str = "heelooiA";
    for(int i = 0; str[i] != '\0'; ++i) {
        for(int x = 0; vowels[x] != '\0'; ++x) {
            if(tolower(str[i]) == vowels[x])
                ++count[x];
        }
    }
    for(int i = 0; i < 5; ++i)
        std::cout << vowels[i] << ": " << count[i] << '\n';
    return 0;
}

Code: http://codepad.org/GA4QPZrA
Last edited on
Topic archived. No new replies allowed.