PDA

View Full Version : identify component,vowel,numeral or special characters


vedzz
10-29-2009, 06:35 PM
i was given a programme to identify no. of consonants, vowels, numerals and special characters in a string which is entered by user. although i have done it but i am looking for a simpler way to this provided that header files i have to use are just iostream.h, conio.h and stdio.h please help me if you have beter than this

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int main()
{
clrscr();
char a[100];
int counter,vowel=0,consonant,numeral;
cout<<"Enter a sentence:"<<endl;
gets(a);
for(counter=0,consonant=0,numeral=0;a[i]!='\0';i++)
{
if(a[counter]=='a' || a[counter]=='e' || a[counter]=='i' || a[counter]=='o' || a[counter]=='u')
vowel++;
else
{
if(int(a[counter])<=91 && int(a[counter])>=65)
consonent++;
if(int(a[counter])>=96 && int(a[counter])<=122)
consonent++;
if(int(a[counter])>=48 && int(a[counter])<=57)
numeral++;
}
}
cout<<"Number of vowels are : "<<vowel<<endl<<"Number of consonants are : "<<consonant<<endl<<"Number of special characters are : "<<counter-consonent-vowel-numeral<<endl<<"Numbers of numerals are : "<<numeral;


getch();
return 0;
}

oracleguy
10-29-2009, 06:43 PM
Four things:

1)
Your character ranges are exclusive so this should be and if elseif sequence:

if(int(a[i])<=91 && int(a[i])>=65)
c++;
if(int(a[i])>=96 && int(a[i])<=122)
c++;
if(int(a[i])>=48 && int(a[i])<=57)
n++;


2)
Use real variable names. You are only punishing yourself by using one letter variable names. Use can call them what they represent, vowels, consonants, etc. It isn't like your program is smaller or more efficient by using shorter variable names.

3) Don't use gets, use cin.getline instead since it will prevent buffer overflows.

4) If you fix number 3, your header files can just be:
#include<iostream>
#include<conio.h>

Fix those things and your program will be much better.

oesxyl
10-29-2009, 10:45 PM
5)
Instead of:

if(int(a[i])<=91 && int(a[i])>=65)
c++;
if(int(a[i])>=96 && int(a[i])<=122)
c++;
if(int(a[i])>=48 && int(a[i])<=57)
n++;

why not:

if(int(a[i])<='[' && int(a[i])>='A') // <-- 91 is '[' why is <= and not <
c++;
if(int(a[i])>='\'' && int(a[i])<='z') // <- same thing for 96
c++;
if(int(a[i])>='0' && int(a[i])<='9')
n++;


best regards