I am suppose to count the number of vowels in a user inputed string.
I dont know what i am doing wrong it gives me one error?

#include <iostream>
#include <string>

using namespace std;

int count_vowels(string str)
{
	int count = 0;
	for (int i = 0; i < str.length(); i++)
	{
		string letter= str.length(i, 1);
		
		if ( letter == "a" || letter=="A" || letter == "e" || letter == "E" || letter == "i" || 
			letter == "I" || letter == "o" || letter == "O" || letter == "u" || letter == "U")
		{
			count++;
		}
	}
		return count;
}

	int main ()
	{
		int count_vowels;
		string str;
		cout << "Please type a word: ";
		cin >> str;
		cout << "There are " << count_vowels << "vowels";
		
		return 0;

	}

Edited 6 Years Ago by WaltP: Added CODE tags -- with all the help about them, how could you miss using them????

This is the error message i get:

1>P5.3.cpp
1>d:\my documents\visual studio 2008\projects\p5.3\p5.3\p5.3.cpp(20) : warning C4018: '<' : signed/unsigned mismatch
1>d:\my documents\visual studio 2008\projects\p5.3\p5.3\p5.3.cpp(22) : error C2660: 'std::basic_string<_Elem,_Traits,_Ax>::length' : function does not take 2 arguments
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1>Build log was saved at "file://d:\My Documents\Visual Studio 2008\Projects\P5.3\P5.3\Debug\BuildLog.htm"
1>P5.3 - 1 error(s), 1 warning(s)

Line 11 you made a mistake that can happen, you typed in the wrong member function, it should be.

string letter = str.substr(i,1);

Line 25 you do not need to create a variable count_vowels since your function can return this value. Also, that variable has the same name as your function, probably not a good idea because of confusion. So comment it out for now then make one more change.

Line 29 don't use that variable you were creating instead just invoke your vowel count function, like so.

cout << "There are " << count_vowels(str) << "vowels";

And one last note, the error you got was for trying to pass 2 variables to the str.length function. And you'll also get a warning for trying to use a variable without initializing it or setting it to a value, like Line 29 was doing.

So just what is that you're trying to do with this statement string letter= str.length(i, 1); ?

Once you fix that, then there's issue that your function is not being used in main( ).


(yeah, what Auto said!)

Edited 6 Years Ago by vmanes: n/a

Got it thank you soo much it was the string letter = str.substr(i,1);

This article has been dead for over six months. Start a new discussion instead.