Cannot count number of consonats.

Hello guys. i need someone help. i cant count the number of consonats.

#include<iostream>
using namespace std;

int main()
{
char dta[100];
int num,i,total;

cout<<"How many character : ";
cin>>num;

1
2
3
4
5
6
7
for(int i=0 ; i<num ; i++)
	{
		cout<<"Enter character NO."<<i+1<<":  " ;
		cin>>dta[i];	
	}
	
	cout<<"The consonant characters :  ";


1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(int i=0 ; i<num ; i++)
	{
	
	if(dta[i]!='a' && dta[i]!='A' &&
	   dta[i]!='e' && dta[i]!='E' &&
	   dta[i]!='i' && dta[i]!='I' &&
	   dta[i]!='o' && dta[i]!='O' &&
	   dta[i]!='u' && dta[i]!='U' )
		{
			cout<<dta[i]<<" ";
			
		
		}
    }


1
2
3
4
5
6
7
8
9
10
11
12
13
for(int i=0 ; i<num ; i++)
	{
		total=0;
		
	if(dta[i]!='a' && dta[i]!='A' &&
	   dta[i]!='e' && dta[i]!='E' &&
	   dta[i]!='i' && dta[i]!='I' &&
	   dta[i]!='o' && dta[i]!='O' &&
	   dta[i]!='u' && dta[i]!='U' )
		{
			total+=dta[i];
		}
    }


cout<<"\nThe total number of consonant is : "<<total<<endl;

return 0;
}
In the last for loop (which you could include in the previous one...) you have to do

++total;

And not total+=dta[i];
its working thanks minomic. i really appreciate.
Ok, you are welcome. The most important part is: do you understand why it works now and was not working before? And can you make some optimization to the code? For example you could have only one for-loop and check the characters while you read them, or you could read a word (not char by char) and then process it...

Anyway, for any other information, just drop me a line.
Last edited on
What if the user enters the code for ' 'or '.' or '$'? You are counting non-vowels, which is not the same thing as counting consonants.

You can do this efficiently with some C library functions:
- tolower() converts a uppercase letters to lower case, leaving other values unchanged.
- isalpha() returns true if the character is a letter
- Both of these take an integer argument that must be a character value or EOF.
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
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int 
main()
{
    string vowels("aeiou");
    string dta;
    unsigned total=0;
    
    while (getline(cin, dta)) {
	for (int i=0; i<dta.size(); ++i) {
	    int ch = (unsigned char)dta[i];
	    if (isalpha(ch) &&
		vowels.find(tolower(ch)) == string::npos) {

		cout << dta[i];
		++total;
	    }
	}
	cout << '\n';
    }
    cout << "total of " << total << " consonants\n";

    return 0;
}

The trickiest part here is line 16. char can be signed so the values are -128 to 127. But you want values 0 to 255. Line 16 does this conversion by converting to unsigned char, which will then get widened to int. Note that int ch = (unsigned)dta[i] doesn't work because the char dta[i] will be widened first, which causes sign extension.

Topic archived. No new replies allowed.