CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Join Date
    Nov 2010
    Posts
    81

    Counting characters help

    I have a program for class where I need to count the number of vowels in one function, then count consonants in another function. I got the vowel one easy. However, I'm a bit stuck on the consonant one. I have my function test if the character is a vowel or whitespace, and skip it. It counts all other characters.

    Two problems - first, i used continue in my vowel/whitespace test and it's getting hung up. What should I use here? Second, how can I account for punctuation? I have an array of "a, e, i, o, u" to test against for vowels... do I need to make one with all the other symbols... or is there a c-type test thing I can use to make it easier, like isalpha (I don't know how I'd use it though)? Here's my function:

    Code:
    int countCons(char *userString, char *vowel)
    {
    	int count = 0;
    	while (*userString != '\0')
    	{
    		if (*userString != *vowel || *userString != ' ')
    			continue; // doesn't work
    		else
    			count++;
    		userString++;
    	}
    	return count;
    }

  2. #2
    Join Date
    Aug 2007
    Posts
    858

    Re: Counting characters help

    "Continue" causes the rest of the loop to be skipped. So when it's triggered, execution just goes back to the start of the loop, meaning you never advance to the next character in the string.

    For your second question, look at http://cplusplus.com/reference/clibrary/cctype/

  3. #3
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    So... is it better to have my code set up like this? (by the way I haven't compiled anything so pardon me if this wouldn't work because of syntax or something... I'm in a hurry right now and can't test it)

    Code:
    int countCons(char *userString, char *vowel)
    {
    	int count = 0;
    	int skip = 0;
    	while (*userString != '\0')
    	{
    		if (*userString != *vowel || *userString != ' ')
    			skip = 0;
    		else if (ispunct(userString))
    			skip = 0;
    		else
    			count++;
    		userString++;
    	}
    	return count;
    }
    I just don't like having a dummy local variable. Isn't there a cleaner way?

  4. #4
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    Re: Counting characters help

    Quote Originally Posted by LogicWavelength View Post
    So... is it better to have my code set up like this? (by the way I haven't compiled anything so pardon me if this wouldn't work because of syntax or something... I'm in a hurry right now and can't test it)

    Code:
    int countCons(char *userString, char *vowel)
    {
    	int count = 0;
    	int skip = 0;
    	while (*userString != '\0')
    	{
    		if (*userString != *vowel || *userString != ' ')
    			skip = 0;
    		else if (ispunct(userString))
    			skip = 0;
    		else
    			count++;
    		userString++;
    	}
    	return count;
    }
    I just don't like having a dummy local variable. Isn't there a cleaner way?
    Code:
    int countCons(char *userString, char *vowel)
    {
    	int count = 0;
    	int skip = 0;
    	while (*userString != '\0')
    	{
    		if (*userString != *vowel && *userString != ' ' && !ispunct(*userString))
    		    count++;
    		userString++;
    	}
    	return count;
    }

  5. #5
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    Wow... duh. Thanks!

  6. #6
    Join Date
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Counting characters help

    What is your char *vowel?
    One vowel? What about the rest of them?
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

  7. #7
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    You know... that is the problem I'm currently dealing with. Suggestions? ha ha...

  8. #8
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    Here's my entire program... I highlighted where I'm currently working (I didn't get to countCons yet.. want the vowels to work first). My test sentence is "I hate this program." and my output says there are 12 vowels and 14 consonants. If I comment out the while loop, the output says there are 10 vowels and 14 consonants. I'm totally lost on the logic here. Here's the code:

    Code:
    /***********************\
    |		Ben B*******	|
    |	Vowels & Consonants	|
    |	Last Mod: 04/03/11	|
    \***********************/
    
    #include <iostream>
    #define SIZE 51
    using namespace std;
    
    int countVowel(char *, char *);
    int countCons(char *, char *);
    
    int main()
    {
    	char userString[SIZE];
    	char vowel[11]={'a', 'e', 'i', 'o' ,'u',
    					'A', 'E', 'I', 'O', 'U'};
    
    	cout	<< "Enter a string (up to 50 characters): ";
    	cin.getline(userString, SIZE);
    
    	cout	<< "There are " << countVowel(userString, vowel) << " vowels, and "
    			<< countCons(userString, vowel) << " consonants in the string." << endl;
    	
    return 0;
    }
    
    int countVowel(char *userString, char *vowel)
    {
    	int count = 0;
    	while (*userString != '\0')
    	{
    		for(int foo = 0; foo < SIZE; foo++)
    		{
    			if (*(userString+foo) == *(vowel+foo))
    				count++;
    			userString++;
    		}
    	}
    	return count;
    }
    
    int countCons(char *userString, char *vowel)
    {
    	int count = 0;
    	while (*userString != '\0')
    	{
    		if (*userString != *vowel && *userString != ' ' && !ispunct(*userString))
    			count++;
    		userString++;
    	}
    	return count;
    }
    Last edited by LogicWavelength; April 4th, 2011 at 08:02 PM.

  9. #9
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Counting characters help

    Quote Originally Posted by LogicWavelength View Post
    Here's my entire program... I highlighted where I'm currently working (I didn't get to countCons yet.. want the vowels to work first). My test sentence is "I hate this program." and my output says there are 12 vowels and 14 consonants. If I comment out the while loop, the output says there are 10 vowels and 14 consonants. I'm totally lost on the logic here.
    First thing is why do you need two separate functions to count vowels and consonants?

    Think for a moment -- what do both of your functions supposed to do? All they do is when given data and criteria for searching, they check if each character matches a character in the criteria. There is no difference other than that.

    Secondly, your inner loop goes up to SIZE, but what if "vowel" is less than SIZE characters? You go off the deep end and you wind up going way past the length of the string. That needs to be fixed.

    Last, you are comparing one character to see if it is within an array of characters. So this is wrong:
    Code:
    	for(int foo = 0; foo < SIZE; foo++)
    		{
    
    			if (*(userString+foo) == *(criteria+foo))
    
    The algorithm is: for each character in userString, test that character within all of the characters in the criteria set.

    Instead you are comparing one userString string character to one criteria character.

    But again, there is no need to write two functions. You only need to write one function, and then call it like this:
    Code:
    int countFunction(const char *userString, const char *criteria)
    {
       // code
    }
    //...
    int main()
    {
        const char*vowel = "aeiou";
        const char* consonant = "bcdfghjklmnpqrstvwxyz";
        
        //...
        int numVowels = countFunction( userInput, vowel );  // get the number of vowels
        int numCons = countFunction( userInput, consonant ); // get the number of consonants
    }
    The sign of a good programmer is one that sees common patterns, and reduces the size of the code based on these patterns. Creating just one function and passing both the user input and the string to be searched is one such example.

    Last, there is a C++ algorithm function, std::count_if(), that makes this even shorter code, and you don't need to write any loops whatsoever.

    Just to let you know that tidbit of information.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; April 4th, 2011 at 10:56 PM.

  10. #10
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    Paul,

    Thanks for the logic help. I am trying to be a good programmer, it's just difficult among 6 classes - one of which is Java! I get so confused (usually with Java, not C++) after hours and hours of staring at code.

    I know that two functions is totally unnecessary - but the book's assignment specifically states to make two. I wish they were one, because then less passing around is needed. Would this be what you're asking for:

    Code:
    for(int foo = 0; foo < vowel; foo++)
    I will get back to this assignment in a few hours, so if I have any more questions, I'll post it up!

    Thanks again everyone. Maybe one day I can offer my help to students too!
    Last edited by LogicWavelength; April 5th, 2011 at 08:40 AM.

  11. #11
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Counting characters help

    Quote Originally Posted by LogicWavelength View Post
    I know that two functions is totally unnecessary - but the book's assignment specifically states to make two.
    Programming is an exact science -- if the description says two separate functions:
    Code:
    int countVowels(const char* userInput)
    {
       return countHelper(userInput, "aeiou");
    }
    
    int countConsonants(const char* userInput)
    {
       return countHelper(userInput, "bcdfghjklmnpqrstvwxyz");
    }
    countHelper is the function I mentioned in my post. See, two separate functions. Also, a good beginner programmer would see that there is redundancy, and would have done something similar to what I wrote above.
    Would this be what you're asking for:
    Code:
    for(int foo = 0; foo < vowel; foo++)
    No.

    There is a library function called strchr() that seaches for a character in a string. I suggest you use it instead of writing another loop.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; April 5th, 2011 at 10:05 AM.

  12. #12
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    I really don't understand what you're trying to tell me... I looked up strchr() and I'm having a really difficult time understanding it, because it uses stuff I haven't learned yet.

    I understand now what you meant by "two" functions, but I really don't understand how I'm supposed to search the strings without a loop... we really haven't learned it yet and the documentation doesn't explain it too great... like printf. what do I #include to get strchr() to work? or do I have to write it myself, using the model in documentation? A few more clues for us mentally challenged...

    EDIT: I found a function in the documentation that suits what I'm trying to do. I still kept my redundant functions because I don't know enough yet on how to pass strings from one function to the other... it wasn't letting me for some reason. This is enough for my assignment, but I still want to find out from here how to improve my skills. Here is my finished program:

    Code:
    /*******************************\
    |	Written by: Ben B*******	|
    |	p.585, #6					|
    |	Vowels & Consonants			|
    |	v1.4 Last Mod: 04/05/11		|
    \*******************************/
    
    #include <iostream>
    #include <string>
    #define VOWEL "aeiouAEIOU"
    #define CONS "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
    using namespace std;
    
    int vowelCount(string, size_t);
    int consCount(string, size_t);
    
    int main ()
    {
    	string input;
    	size_t found = 0;
    	cout	<< "Please enter a string: ";
    	getline(cin, input);
    
    	int numVowels = vowelCount(input, found);
    	int numCons = consCount(input, found);
    
    	cout	<< "There were " << numVowels << " vowels and " << numCons << " consonants in the string.\n"
    			<< "There were " << numVowels+numCons << " total characters in the string." << endl;
    
    	return 0;
    }
    
    int vowelCount(string input, size_t found)
    {
    	int numVowel = 0;
    	found=input.find_first_of(VOWEL);
    	while (found!=string::npos)
    	{
    		numVowel++;
    		found=input.find_first_of(VOWEL,found+1);
    	}
    	return numVowel;
    }
    int consCount(string input, size_t found)
    {
    	int numCons = 0;
    	found=input.find_first_of(CONS);
    	while (found!=string::npos)
    	{
    		numCons++;
    		found=input.find_first_of(CONS,found+1);
    	}
    	return numCons;
    }
    How can I send strings around, to arrange my functions like you said (with two functions simply using a 3rd workhorse function) as well, I have a little data validation while loop thing I usually encapsulate my programs in, asking if the user wishes to run them. Whenever I do that with this program, it immediately outputs everything in the while loop and asks me to run it again but every other program it copies/runs fine.... why is that? I can put the loop here if you need it...
    Last edited by LogicWavelength; April 5th, 2011 at 01:37 PM.

  13. #13
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Counting characters help

    Quote Originally Posted by LogicWavelength View Post
    I really don't understand what you're trying to tell me... I looked up strchr() and I'm having a really difficult time understanding it, because it uses stuff I haven't learned yet.
    So write a program that uses it, so that you understand exactly what it's supposed to do.

    http://www.cplusplus.com/reference/c...string/strchr/

    Look at the example above.
    Code:
    #include <cstring>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        const char *str = "This is a test";
        const char *foundPos = strchr(str, 'a');
        if ( foundPos )
             cout << "I found an 'a'";
        else
             cout << "I didn't find an 'a'";
    }
    You should write small test applications if you don't know how a function is supposed to work.
    I understand now what you meant by "two" functions, but I really don't understand how I'm supposed to search the strings without a loop...
    Look at the example above -- I searched the string "This is a test", without a loop.

    So what I'm asking you to do is use strchr() to see if a letter in the string to search is a vowel or if it's a consonant. Right now, you're writing a (faulty) search loop to do that, when clearly, given strchr(), you do not need to write it.
    Code:
    const char *foundpos = strchr("aeiou", character_in_the_userinput_I_am_testing);
    if (foundpos)
    {
        // character I'm testing is a vowel
    }
    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; April 5th, 2011 at 01:38 PM.

  14. #14
    Join Date
    Nov 2010
    Posts
    81

    Re: Counting characters help

    Here is my "re-run" loop. Whenever I place the program in here, it doesn't work - but it has with every single other program I've written. Help?

    Code:
    int main()
    {
    	//--INITIATE PROGRAM--//
    	char rerun;
    	bool valid = false;
    	while (valid == false)
    	{
    		cout	<< "Would you like to run this program (y/n)?: ";
    		cin		>> rerun;
    
    		//validate input
    		if (rerun == 'y' || rerun == 'Y' || rerun == 'n' || rerun == 'N')
    			valid = true;
    	}
    	
    	//--START PROGRAM--//
    	while (rerun == 'y' || rerun == 'Y')
    	{
    		//--PROGRAM GOES HERE--//
    
    		valid = false;
    		while (valid == false)
    		{
    			cout	<< "Would you like to run this program again (y/n)?: ";
    			cin		>> rerun;
    			system("cls");
    
    			//validate input
    			if (rerun == 'y' || rerun == 'Y' || rerun == 'n' || rerun == 'N')
    				valid = true;
    		}
    	}
    	cout	<< "HAVE A NICE DAY!" << endl;
    	return 0;
    }

  15. #15
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    Re: Counting characters help

    That's an odd way to do it, but what do you mean "doesn't work"?

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured