Counting vowels and storing non-vowels into array

I would like to store any non-vowels in notvowel[] and display them but I'm not sure how to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>

using namespace std;

int main()
{
	char letter[30] = "welcome to touch n go";
	char notvowel[15] = {NULL };
	
	int vowels = 0;
	for (int i = 0; letter[i] != '\0'; ++i)
	{
		if (letter[i] == 'a' || letter[i] == 'e' || letter[i] == 'i' ||
			letter[i] == 'o' || letter[i] == 'u' )
		{
			++vowels;
		}
		

	}
	cout << "Vowels: " << vowels << endl;
	
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cctype>
#include <string>

using namespace std;

int main(){

    const string vowel="aeiouy";

    string letter="welcome to touch n go";
    string notvowel;

    for(int i(0);i<letter.size();++i){
        if(vowel.find_first_of(tolower(letter[i]))==string::npos) notvowel+=letter[i];
    }

    cout<<notvowel<<endl;

    return 0;
}
Last edited on
Here is an implementation using a different function with C++17, just in case you plan on extending this program or using this code in another program. It seperates vowels and nonvowels to seperate std::vectors (you can use them just like a char array):

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
36
37
38
39
#include <iostream>
#include <vector>
#include <string_view>
#include <utility>

bool is_vowel(char ch) //Converts character to upper and determines if said character is a vowel
{
    ch = toupper(ch);
    return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) ;
}

using char_vec = std::vector<char>;
using vowel_nonvowel_pair = std::pair<char_vec, char_vec>;

vowel_nonvowel_pair count_vowels(std::string_view str) //Return a vector pair of vowels/nonvowels
{
    std::vector<char> vowels, nonvowels;
    for (auto i : str) (is_vowel(i) ? vowels.push_back(i) :nonvowels.push_back(i) );
    return std::make_pair(vowels, nonvowels);
}

int main()
{
    auto [Vowels, Nonvowels] = count_vowels("Hello World! My name is Groot."); //C++17 structured bindings.
    std::cout << "Original Text: Hello World! My name is Groot.\n";
    std::cout << "Vowels: ";

    for (auto i : Vowels)    std::cout << i;

    std::cout << "\nConsonants and Nonvowels: ";

    for (auto i : Nonvowels) std::cout << i;
    
    std:: cout << "\n# of Vowels: " << Vowels.size() << '\n';
    std:: cout << "# of Nonvowels: "<< Nonvowels.size() << '\n';
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.