我在 C++ Primer Plus 书中第 6 章的第 7 个练习中遇到了一些问题。好吧,我认为我把这个练习做得很好,但我的编译器不这么认为。该程序应计算单词开头的元音、辅音和其他字符的数量。问题是它计算元音而不是辅音,辅音而不是元音。
例如:如果我输入“a e o i u”,它表示我输入了 5 个以辅音开头的单词。
提前感谢您的解释。
代码如下:
#include <iostream>
#include <cstring>
char word[20];
int others=0;
int vowels=0;
int consonants=0;
int main()
{
std::cout<<"Enter words (q to quit):";
std::cin>>word;
while(strcmp(word,"q"))
{
word[0]=tolower(word[0]);
if(!isalpha(word[0]))
others++;
else if(word[0]!='a'&&word[0]!='e'&&word[0]!='i'&&word[0]!='o'&&word[0]!='u')
consonants++;
else vowels++;
std::cin>>word;
}
std::cout<<vowels<<" words beginning with vowels\n";
std::cout<<consonants<<" words beginning with consonants\n";
std::cout<<others<<" others";
return 0;
}
最佳答案
这里的原因是当您键入 e i o u 'they' 作为 5 个不同的词输入到 std::cin 时。因为,这种情况下的cin以空格作为单词分隔符,迭代5次后会提示输入新单词。所以这是正确的。如果你输入 e i o u q 那么你将不会再次被提示输入任何输入,因为第 6 个单词是 q 应该从你的循环中退出。所以行为是正确的。
如果您调试程序,您可以了解真正发生的事情。
关于C++ Primer 计数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463349/