Reputation: 7
I've been able to count number of syllables in a word by making a simple nested for loop, but can't figure out how to rewrite such an algorithm that ensures any multiple vowels right next to each other in a word count as just one syllable. I've only come across one other example using pointers, my question is if there's any other approach as I just started learning pointers this week and am not sure how to use them properly.
This is my program so far:
#include <iostream>
#include <string>
using namespace std;
void indexfx(string sentence);
int main(void)
{
string user;
cout << "\n\nPlease Enter a Sentence: ";
getline(cin, user);
indexfx(user);
return 0;
}
void indexfx(string sentence)
{
string vowels = "aeiouy";
int syllables = 0;
for(unsigned int i = 0; i < sentence.size(); i++)
{
for(unsigned int j = 0; j < vowels.size(); j++)
{
if(sentence[i] == vowels[j]
{
syllables++;
}
}
}
cout << syllables;
}
Upvotes: 0
Views: 1197
Reputation: 275720
This is a state machine.
Vowel Consonant EndOfWord
C V C End
V V C* End*
where *
means "increase syllable count". Start in state C
.
Tests:
a*da*m ma*da*m he*llo* chi*cke*n
We can implement this state machine directly:
int count_syllables( std::string s ) {
int count = 0;
char state = 'c';
for (auto c : s ) {
switch(state) {
case 'c': {
break;
}
case 'v': {
if (!IsVowel(c)) ++count;
break;
}
}
state = IsVowel(c)?'v':'c';
}
if (state == 'v') ++count;
return count;
}
now we just need to write IsVowel
.
bool IsVowel(char c) {
static const std::string vowels = "aeiouy";
return vowels.find(c) != std::string::npos;
}
Upvotes: 1
Reputation: 217785
By using std::string
methods, you might do:
void indexfx(const std::string& sentence)
{
const std::string vowels = "aeiouy";
int syllables = 0;
std::string::size_type offset = 0;
while (offset != std::string::npos) {
offset = sentence.find_first_of(vowels, offset);
if (offset == std::string::npos) { break; }
++syllables;
offset = sentence.find_first_not_of(vowels, offset);
}
std::cout << syllables << std::endl;
}
Upvotes: 0
Reputation: 198418
If you find a vowel, don't immediately go incrementing syllable count. Instead, have a flag that you found a vowel. It starts off as false, as you haven't had time to search yet; if you find one, flip it to true and break out of the vowel loop.
Have another flag that remembers whether the previous letter was a vowel. Now only increase the syllable count if the current letter is a vowel and the previous one wasn't.
Before the letter loop restarts, at the very bottom, remember that the vowelhood of the last letter in the next cycle is the vowelhood of the current letter in the current cycle.
Note that this answer is just getting your code to what you state you want it to do: ignore consecutive vowels. The algorithm itself is not a reliable way to find the syllable count, as English is a bit crazy in this respect. See Counting Syllables In A Word for more details.
Upvotes: 0