gpt4 book ai didi

c++ - 当一切正确时,代码继续打印 "1"

转载 作者:行者123 更新时间:2023-11-30 02:33:13 24 4
gpt4 key购买 nike

代码运行,但它没有打印出元音,而是打印出一个“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;

}

输出应该是这样的:

输入一句话或a退出:我喜欢苹果!

你的句子中有 4 个元音字母和 11 个字母。

输入一句话或q退出:q

再见!

我的问题:有人可以向我解释为什么它一直打印“1”,而我应该分配热键“q”以退出程序的“if”语句不起作用。当我运行该程序时,我在 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 计数,只需在函数中创建它,并记得返回它。

关于c++ - 当一切正确时,代码继续打印 "1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com