To find number of vowels.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "stdafx.h"


#include <iostream>
#include <string>
int main(){
	std::string vowelor[] {"My name is Matilda"}{
		for (int i = 0; i < vowelor[3].length; i++){
			if (i == "a" || i == "e" || i == "o" || i == "u"){
				int a = 0;
				a = a + 1;
			}
		}
	}

I don't know what to do with the underlined bracket( after {"My name is Matilda"} at the end of line 7) , I tried semicolons and both but there's still an error.Also I think I'm sure there's another logical error with the program, but I don't know..help please.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <stdlib.h>

int main(void)
{
  std::string name = "My name is Matilda";
  size_t vowel_count = 0;

  for (size_t i = 0; i < name.length(); i++)
  {
    if (name[i] == 'a' || name[i] == 'e' || name[i] == 'o' || name[i] == 'u' || name[i] == 'i')
    {
	vowel_count++;		
    }
  }
  std::cout << "The string '" << name << "' contains " << vowel_count << " vowels." << "\n\n";
  
  system("pause");
  return 0;
}
Can't I do it with an array? I want to practice arrays^^
Last edited on
It is possible with arrays.
I'll show you just the declaration of the array:

 
std::string name[4] = {"My", "name", "is", "Matilda"};
Last edited on
Thank you :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"





#include <iostream>
#include <string>
int main(){
	std::string vowelor[] {"My", "name", "is", "Matilda"}{
		for (int i = 0; i < vowelor[3].length; i++){
			if (i == "a" || i == "e" || i == "o" || i == "u"){
				int a = 0;
				a = a + 1;
			}
		}
	}

	}

I'm still having a problem, and I don't know what it is, should I re-read the arrays and loops tutorials?
remember to use subscript because strings are objects like arrays

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
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
	//initialise array of words
	string words[] = { "My", "name", "is", "Matilda" };

	//N number of words, M number of letters of a word
	int N = 4, M;
	int nr;

	for (int i = 0; i < N; i++)
	{
		nr = 0;
		M = strlen(&words[i][0]); //get length of current word
		//strlen takes as argument the adress of the first position of a array(strings are like arrays)
		//so you pass the first position of the current word with & in front

		for (int j = 0; j < M; j++)
		{
			//if the current character of the current word is a vowel increment nr
			if (strchr("aeiouAEIOU", words[i][j]) != NULL)
				nr++;
		}

		cout << words[i] << " has " << nr << " vowels" << endl;
	}
}
Topic archived. No new replies allowed.