【发布时间】:2020-01-24 17:55:12
【问题描述】:
我创建了一个程序来计算用户输入的单词中的音节。用户要输入任意数量的单词,然后按 Enter 键,直到输入 (#) 键,然后程序将在表格中显示单词,然后是每个单词的音节数。
我的程序的“静音 e”部分有问题。
if (word_length - 1 == 'e')
{
vowels = vowels - 1;
似乎它无法拾取单词串中的最后一个字母。我试图移动一些 if 语句以查看是否有帮助并更好地确定问题所在,并且根据我所注意到的,如前所述,我相信它与代码的静默 e 部分有关。 在我的代码中即使是最小的错误也很难找到,所以我要求另一双眼睛盯着我的代码。 任何帮助将不胜感激。 另外,我还没有完成我的结果表的格式,所以请看一下。
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
string word_1 = "create list";
int vowels = 0;
int word_length; // better to set .length() into variable to eliminate warnings
int words_to_print = 0; // this will count how many words to print to use in for loop later
/*
vector <variable type> name_of_vector[size of vector];
creating vectors
leaving them empty for now
*/
vector <string> words_saved;
vector <int> number_of_syllables_saved;
cout << "Enter 4 words from the English dictionary, to determine the amount of syllables each word has." << endl;
cout << "Please enter [#] when finished, to create a list." << endl;
cin >> word_1;
while (word_1 != "#") // as long as user doesnt enter # you can enter a word and
{ // have it run thru the syllable logic
word_length = word_1.length();
words_to_print++;
words_saved.push_back(word_1);
// ^ this saves the word into the next availabe index of vector for strings.
for (int i = 0; i < word_length ; i++) // length is a variable now instead of function syntax this
{ // eliminates the <: signed/usnsigned mismatch warning below
if ((word_1[i] == 'a') || (word_1[i] == 'e') || (word_1[i] == 'i') || (word_1[i] == 'o') || (word_1[i] == 'u') || (word_1[i] == 'y'))
{
vowels = vowels + 1;
if ((word_1[i + 1] == 'a') || (word_1[i + 1] == 'e') || (word_1[i + 1] == 'i') || (word_1[i + 1] == 'o') || (word_1[i + 1] == 'u') || (word_1[i + 1] == 'y'))
{
vowels = vowels - 1;
if (word_length - 1 == 'e')
{
vowels = vowels - 1;
if (vowels == 0)
{
vowels = vowels + 1;
}
}
}
}
}
number_of_syllables_saved.push_back(vowels);
//^ this puts number of syllables into vector of ints
vowels = 0; // this resets the amounts so it can count vowels of next word and not stack from previous word
cin >> word_1; // this will reset the word and controls loop to print out chart if # is entered
}
// use a for loop to print out all the words
cout << endl << endl << endl;
cout << "Word: " << setw(30) << "Syllables: " << endl;
for (int x = 0; x < words_to_print; x++)
{
cout << words_saved[x] << setw(20) << number_of_syllables_saved[x] << endl;
}
//system("pause");
return 0;
}
【问题讨论】:
-
word_length - 1 == 'e'。你比较一个长度和一个字符。是故意的吗?您是指 word_1[word_length-1] 还是类似的意思?
-
当
i为word_length-1时访问word_1[i + 1]未定义。 -
感谢您的回复;不,我打算使用后者,word_1 [word_length - 1]。但是,在进行更改后,我的程序仍然没有为大多数单词选择静音 e。它确实为“the”提供了正确的音节计数,我认为这与第一个 if 语句有关,因为单词中只有 1 个元音。
-
@molbdnilo 您介意详细说明“i 是 word_length - 1 它是未定义的”是什么意思吗?
-
@user12776943 未定义意味着您的程序可以做任何事情。如果你使用的是 C++11 或更高版本,它是安全的。