Question

C++ counting vowels and consonants

Asked by: veeaechone

I need to write a program that uses both a C-string and a string data type.  I have the C-string type working but I'm not sure how to incorporate the string data type.  Can someone point me in the right direction.  I found an example in Experts Exchange but it does not work properly and is somewhat different from mine.  Any help would be appreciated.

#include<iostream>
using namespace std; 
int main()
{
 int n[256]={0}; // an array to hold the count of all characters entered
 int consonants=0,vowels=0,characters=0; // number of consonants, vowels, words & characters
 char user_input[255]; // the user input
 cout<<"Enter a string:"<<endl;
 
 cin.getline(user_input,255); // get the user input
 cout<<"You entered: "<<user_input<<endl;
 
 for(int c=0;user_input[c]!='\0';++c) // loop through the entire user input
 {
  ++n[user_input[c]]; // add 1 to the array holding the count of each character
  
 }
 
 
 vowels=n['A']+n['a']+n['E']+n['e']+n['I']+n['i']+n['O']+n['o']+n['U']+n['u'];
 
 consonants=n['B']+n['b']+n['C']+n['c']+n['D']+n['d']+n['F']+n['f']+n['G']+n['g']+n['H']+n['h']+n['J']+n['j']+n['K']+n['k']+n['L']+n['l']+n['M']+n['m']+n['N']+n['n']+n['P']+n['p']+n['Q']+n['q']+n['R']+n['r']+n['S']+n['s']+n['T']+n['t']+n['V']+n['v']+n['W']+n['w']+n['X']+n['x']+n['Y']+n['y']+n['Z']+n['z'];
 
 characters=n['A']+n['a']+n['B']+n['b']+n['C']+n['c']+n['D']+n['d']+n['E']+n['e']+n['F']+n['f']+n['G']+n['g']+n['H']+n['h']+n['I']+n['i']+n['J']+n['j']+n['K']+n['k']+n['L']+n['l']+n['M']+n['m']+n['N']+n['n']+n['O']+n['o']+n['P']+n['p']+n['Q']+n['q']+n['R']+n['r']+n['S']+n['s']+n['T']+n['t']+n['U']+n['u']+n['V']+n['v']+n['W']+n['w']+n['X']+n['x']+n['Y']+n['y']+n['Z']+n['z'];
 
  
 cout<<"This has "<<characters<<" characters, "<<vowels<<" vowels and "<<consonants<<" consonants"<<endl; // data type
 
 cin.get();
 return 0;
}

                                  
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:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-10 at 17:32:36ID24641847
Tags

C++

Topic

C++ Programming Language

Participating Experts
5
Points
500
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Counting long a Text String is
    I have a Variable called Var1 & I need a way of counting how long the variable is, what is the best way? Something like Var1 = "This is my Text String" Count_Of Var1 = Mid(Var1,Count) Count = Count +1 And then loop it until it reaches the end? or is there a...
  2. Counting Number of 'A's in a String
    Does anyone know how to count the total number that a certain character shows up in a string? I want my function to count how many 'A's are in my string... Any help?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jhshuklaPosted on 2009-08-10 at 20:32:32ID: 25065997

If your code is working for c-style strings, then changing to stl strings is easy.

std::getline(cin, user_input);
for(int c=0;c !=user_input.length();++c)


this is optional:
you don't need to create 256-count array. you can achieve the same results with size 26 using


 

by: WhiteMagePosted on 2009-08-10 at 22:11:56ID: 25066283

How about this?

#include <cctype>
#include <cstring>
#include <iostream>
#include <string>
 
int main(int argc,char **argv) {
	bool useStrInput = true; //change this to false to use C-string
 
	int counts[26];
	int characters = 0,
		consonants = 0,
		vowels = 0;
	for(int i = 0; i < 26; i++) {
		counts[i] = 0;
	}
 
	std::cout << "Enter a string:" << std::endl;
 
	if(useStrInput) {
		std::string str_input;
		std::getline(std::cin,str_input);
		std::cout << "You entered: " << str_input << std::endl;
 
		for(unsigned int j = 0; j < str_input.length(); j++) {
			int c = std::toupper(str_input[j]) - 'A';
			if(c >= 0 && c <= 25) {
				++counts[c];
			}
		}
	}
	else {
		char cstr_input[256];
		std::cin.getline(cstr_input,256);
		std::cout << "You entered: " << cstr_input << std::endl;
 
		for(unsigned int j = 0; j < std::strlen(cstr_input); j++) {
			int c = std::toupper(cstr_input[j]) - 'A';
			if(c >= 0 && c <= 25) {
				++counts[c];
			}
		}
	}
 
	consonants = counts['B' - 'A'] + counts['C' - 'A'] + counts['D' - 'A']
			+ counts['F' - 'A'] + counts['G' - 'A'] + counts['H' - 'A']
			+ counts['J' - 'A'] + counts['K' - 'A'] + counts['L' - 'A']
			+ counts['M' - 'A'] + counts['N' - 'A'] + counts['P' - 'A']
			+ counts['Q' - 'A'] + counts['R' - 'A'] + counts['S' - 'A']
			+ counts['T' - 'A'] + counts['V' - 'A'] + counts['W' - 'A']
			+ counts['X' - 'A'] + counts['Y' - 'A'] + counts['Z' - 'A'];
	vowels = counts['A' - 'A'] + counts['E' - 'A'] + counts['I' - 'A'] + counts['O' - 'A'] + counts['U' - 'A'];
	characters = consonants + vowels;
 
	std::cout << "This has " << characters << " characters, "
			<< vowels << " vowels, and "
			<< consonants << " consonants." << std::endl;
 
	return(0);
}
                                              
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:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:

Select allOpen in new window

 

by: Infinity08Posted on 2009-08-10 at 22:44:56ID: 25066399

>> you can achieve the same results with size 26 using

You don't even need an array, since you can increments the vowels, consonants and characters counters inside the loop. That will be by far a cleaner way.

Regarding your question about strings, take a look at what's available in the standard C++ strings library :

        http://cplusplus.com/reference/string/

 

by: itsmeandnobodyelsePosted on 2009-08-11 at 01:27:59ID: 25067012

>>>> You don't even need an array
The array has the advantage that the index can be computed from character code.

Counting vowels and consonants in the loop would require an if-else statement in the loop which is not so elegant.

A compromise could be using a switch statement which combines both benefits:


 getline(cin, user_input); // assuming user_input is std::string
 for(int c=0; c < (int)user_input.size(); ++c) // loop through the entire user input
 {
     switch (c)
     {
         case 'A': case 'a:' case 'E': case 'e': case 'I' case 'i': case 'O': case 'o': case 'U': case 'u':
              ++vowels; break;
         default:
              if (isalpha(c) == TRUE)
                  ++consonants;
              else
                  ++characters;
              break;
     }
     characters += vowels + consonants;
 
Of course you could use a  case 'B': case 'b': case 'C' ... for consonants as well what would spare the if statement in the default branch.

 

by: Infinity08Posted on 2009-08-11 at 02:26:42ID: 25067267

>> Counting vowels and consonants in the loop would require an if-else statement in the loop which is not so elegant.

Two nested if statements is all you need. Nothing inelegant about that ;) In fact, it looks pretty clear to me :

if (isalpha(c)) {
  ++characters;
  if (isvowel(c)) {
    ++vowels;
  }
  else {
    ++consonants;
  }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: itsmeandnobodyelsePosted on 2009-08-11 at 03:01:32ID: 25067416

>>>> Two nested if statements is all you need. Nothing inelegant about that ;)

 ;-)



     switch (c)
     {
         case 'A': case 'a:' case 'E': case 'e': case 'I' case 'i': case 'O': case 'o': case 'U': case 'u':
              ++vowels; break;
         default: consonants += isalpha(c); break;
     }
     characters = vowels + consonants; 

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: itsmeandnobodyelsePosted on 2009-08-11 at 03:02:32ID: 25067418

>>>> characters = vowels + consonants;
should be outside of the loop

 

by: veeaechonePosted on 2009-08-11 at 05:47:58ID: 25068314

You guys are great!  These are all very helpful!  A couple of things...an array was required for this exercise and I also have to make BOTH the C-string and string data type work at the same time.  I have to have two outputs using both methods.  I'm having a problem understanding how to make them both work at the same time.  Again, please and thank you, and you guys are great!

 

by: Infinity08Posted on 2009-08-11 at 05:49:46ID: 25068341

>> an array was required for this exercise

fair enough :)


>> and I also have to make BOTH the C-string and string data type work at the same time.

What did the exact assignment state ? Because I'm not sure how to interpret this.

 

by: WhiteMagePosted on 2009-08-11 at 05:50:33ID: 25068350

The point of the array is for speed only (less if/switch statements); however, the isalpha and "isvowel" approach is more elegant.  It is merely what the programmer desires.

 

by: WhiteMagePosted on 2009-08-11 at 05:54:56ID: 25068397

>> I also have to make BOTH the C-string and string data type work at the same time.

To allow this to use both, look at the code between "if(useStrInput) {...}else{...}"  You can break these blocks into two separate functions.  Then do something like:

std::string str_input = doStrInput();
char *cstr_input = doCStrInput(); //char * doCStrInput() { char cstr_input[256]; ... return(cstr_input); }

If there is something wrong with my solution, please let me know. Thanks.

 

by: veeaechonePosted on 2009-08-11 at 05:55:04ID: 25068399

Here are the instructions:

Write a program that prompts the user to input a string. The output will be the total number of characters in the string, the total number of consonants in the string, and the total number of vowels in the string. Be sure to prompt for input and to label your output. The code needs to handle the string as a character array (C-string) and as a string data type - so this means that you will see the same output twice, once for a C-string and once for a string data type.  Be sure to find the length of your c-string and the length of your string separately, using functions specific to c-string and string variables.

 

by: WhiteMagePosted on 2009-08-11 at 05:59:27ID: 25068429

Because this is a homework asgmt, try to see if you can use my code in my first post to print out both cstr_input and str_input.  Actually, I think all you need to do is just take out the if statement and don't need separate functions unless you want to.  I do minus 'A' because 'A' is the lowest # so everything will fall between 0 and 26.  Ignore my most recent post above this one (wish you could delete or edit posts).

 

by: veeaechonePosted on 2009-08-11 at 06:05:47ID: 25068492

To WhiteMage - I will try that, Thanks!

 

by: WhiteMagePosted on 2009-08-11 at 06:20:30ID: 25068657

You're welcome; you'll need separate variables (all variables) for each C-string and string.  All I can suggest further is to mess with the code I posted.  Try to figure out how everything is working and have fun.  The best way to learn a programming language is messing around with it.  Just like any other language, you can't learn it for the final exam with just one all-nighter.  You have to work with it.  See what happens when you do this, etc.  But most importantly just have fun.

 

by: veeaechonePosted on 2009-08-11 at 06:24:12ID: 25068705

I appreciate your help and I do want to try to figure it out on my own.  It is the best way to learn.  I am limited on time though so if you could offer advice on the best route to take such as:  would it be easier to have to different methods or will I figure it out faster keeping it together as it is?  Thanks.

 

by: flob9Posted on 2009-08-11 at 06:51:46ID: 25068999

Isn't the character count the length of the string ? I'll consider spaces, digits, punctuation as characters ...


 

by: Infinity08Posted on 2009-08-11 at 06:55:15ID: 25069036

>> I am limited on time though so if you could offer advice on the best route to take

Try to get it working for the C string only first.
Then try to get it working for the C++ string only.

Once you have two separate pieces of code that work, you can combine them to get the final code that has outputs for both approaches.

 

by: WhiteMagePosted on 2009-08-11 at 07:07:54ID: 25069203

>> Isn't the character count the length of the string ? I'll consider spaces, digits, punctuation as characters ...

In programming, yes.  If you open up Microsoft Word, it only counts consonants and vowels (at least in the version I'm using).  In English Literature, generally speaking, spaces, digits, and punctuation marks aren't considered characters.  Ultimately, it depends on what her teacher wants, whatever that is.

>>  I am limited on time though so if you could offer advice on the best route to take such as:  would it be easier to have to different methods or will I figure it out faster keeping it together as it is?

Just keep it together, this will be faster.  Here is what you'll basically need to do:

//separate variables for both methods ("string" and "c-string" method)
std::string str_input;
char cstr_input[256] = {0};
int str_counts[26] = {0},cstr_counts[26] = {0};
int str_c = 0,str_v = 0,cstr_c = 0,cstr_v = 0; //c=consonants; v=vowels

//get input from user using str_input
//count everything using str_counts, str_c, and str_v

//get input from user using cstr_input
//count everything using cstr_counts, cstr_c, and cstr_v

//output results as (str_c + str_v), str_c, and str_v
//output results as (cstr_c + cstr_v), cstr_c, and cstr_v

 

by: itsmeandnobodyelsePosted on 2009-08-11 at 12:44:47ID: 25072605

>>>> The code needs to handle the string as a character array (C-string) and as a string data type - so this means that you will see the same output twice, once for a C-string and once for a string data type.  Be sure to find the length of your c-string and the length of your string separately, using functions specific to c-string and string variables.

Though the instructions were using many words to emphasize the bivalence of C/C++ strings, it is neither a necessity to use both C char arrays and C++ string for that task nor is it senseful to do so.

IMO, it would be best to take your first post which looks at the input as to a C string - probably improved by some of the suggestions which also are C compatible - as one of two alternative solutions. Then you could add a pure C++ solution using std::string and no char arrays.

Note, the switch statment, the isvowel and isalpha functions take an int or char type as operand what is without alternative valid for both C *AND* C++, i. e. you could use them in either of the solutions.

If you nevertheless want a mixed solution I would suggest to have a C++ only user input using std::string and do the evaluation of the input string after a statement like

    const char * pszUserInput = user_input.c_str();

After that use C code only, e. g. use strlen to determine the length of input.

   

 

by: veeaechonePosted on 2009-08-12 at 17:50:58ID: 31614006

Thanks again.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...