代码保持印刷“1”时,一切是正确的
问题描述:
代码运行并一切,但它不打印出来的元音,而是打印出“1”。代码保持印刷“1”时,一切是正确的
#include <iostream>
#include <string>
using namespace std;
int countVowels(string sentence,int numVowels)
{
for(int i =0; i<sentence.length(); i++)
{
if((sentence[i]==('a'))||(sentence[i]==('e'))||(sentence[i]==('i'))||(sentence[i]==('o'))||(sentence[i]==('u'))||(sentence[i]==('A'))||(sentence[i]==('E'))||(sentence[i]==('I'))||(sentence[i]==('O'))||(sentence[i]==('U')))
numVowels=numVowels+1;
}
}
int main()
{
string sentence;
int numVowels = 0;
do{
cout << "Enter a sentence or q to quit: ";
cin >> ws;
getline(cin,sentence);
}
if(sentence == 'q'|| sentence == 'Q');
cout << "There are " << countVowels << " vowels in your sentence." << endl;
return 0;
}
输出应该是这样的:
输入一个句子或退出:我喜欢苹果!
有4个元音字母在你的句子,以及11个字母。
输入一句话或q退出:q
再见!
我的问题: 可为什么它一直印一个“1”,我的“如果”的声明,其中我应该分配热键“Q”退出程序不工作有人向我解释。当我运行程序我在if语句说:“敌不过运营商==”
答
我通常不喜欢只是提供了一个完整的解决方案,但因为你的问题说明你已经有了一个良好的努力得到一个错误,这里是我会怎么写呢(当然,不完全的,我简单一点更方便初学者):
#include <algorithm>
#include <iostream>
#include <string>
bool isVowel(char c)
{
// A simple function that returns true if the character passed in matches
// any of the list of vowels, and returns false on any other input.
if ('a' == c ||
'e' == c ||
'i' == c ||
'o' == c ||
'u' == c ||
'A' == c ||
'E' == c ||
'I' == c ||
'O' == c ||
'U' == c) {
return true; // return true if it's a vowel
}
return false; // remember to return false if it isn't
}
std::size_t countVowels(std::string const& sentence)
{
// Use the standard count_if algorithm to loop over the string and count
// all characters that the predicate returns true for.
// Note that we return the resulting total.
return std::count_if(std::begin(sentence),
std::end (sentence),
isVowel);
}
int main() {
std::string sentence;
std::cout << "Please enter a sentence, or q to quit: ";
std::getline(std::cin, sentence);
if ("q" == sentence ||
"Q" == sentence) {
// Quit if the user entered a string containing just a single letter q.
// Note we compare against a string literal, not a single character.
return 0;
}
// Call the counting function and print the result.
std::cout << "There are "
<< countVowels(sentence) // Call the function on the input.
<< " vowels in your sentence\n";
return 0;
}
希望这些评论使这一切清楚。
现在你可能已经被告知不能使用标准算法(std::count_if
),因为练习的一部分似乎是要写这个算法。那么我会把它留给你。您目前的版本接近正确,但请记得返回结果。而且你并不需要传递numVowels
计数,只需在函数内创建它,并记住将其返回。
+0
优秀的答案。正确,简单,对未来的读者非常有用。我喜欢这样! – Kevin
没有'做{...}如果()'。拿出'do {}'。在if后面(删除';'),添加'{return 0; }'在这里结束程序。然后你需要实际调用你的句子上的函数:'countVowels(sentence,0)'。 – BoBTFish
哦,你不能比较'std :: string'对单个字符。最简单的解决方法就是用'q'替换''q''(字符串文本),对'Q''也是如此。 – BoBTFish
此外,在countVowels结束(),你需要'返回numVowels;' – aron9forever