-
Strings and stuff
Hi all,
I'm having trouble diagnosing a while loop I created to analyze a string's number of vowels and consonants. Here is my code:
while (string[i] != '\n')
{
if (string[i] == 'a' )
vowels++;
else
consonants++;
i++;
}//end of analyzing loop
Some help would be greatly appreciated.
-
For a start, the condition tests for '\n' not '\0' or NULL.....
What other problems have you got?
-
Counting vowels
I think I need one more tweak to make the whole engine work. The change from '/n' to '/0' worked, but the loop doesn't separate the vowels from the consonants. Instead, it counts all the characters as vowels.
Here is the code I used:
char string[256];
int vowels=0, consonants=0;
cout << "Input string: ";
cin.getline( string, 256, '\n');
cout << "You typed: " << string << endl;
int i=0;
while (string[i] != '\0')
{
if (string[i] == 'a' || 'e' || 'i' || 'o' || 'u' )
vowels++;
else
consonants++;
i++;
}//end of analyzing loop
char string[256];
int vowels=0, consonants=0;
cout << "Input string: ";
cin.getline( string, 256, '\n');
cout << "You typed: " << string << endl;
int i=0;
while (string[i] != '\0')
{
if (string[i] == 'a' || 'e' || 'i' || 'o' || 'u' )
vowels++;
else
consonants++;
i++;
}//end of analyzing loop
cout << "Number of vowels in your string: " << vowels << endl;
cout << "Number of non-vowels in your string:" << consonants << endl;
-
Code:
if (string[i] == 'a' || 'e' || 'i' || 'o' || 'u' )
not legal!!!
Have to include seperate equals statements. Use a newline for each vowel comparison to make ur code look neat.
if (string[i]=='a' ||
string[i]=='b' ||
and so on...
-
Good call! I had a similar line work in a different application (with int) so I never suspected that illegality. Thanks!