我在写一些代码,遇到了一些麻烦。我想编写一个检查字符串是否有元音的函数,并尝试通过内部带switch语句的for循环来实现。显然,它不起作用,并且由于某种原因永远不会返回true。
bool scanStr(string userInp) {
for (int i = 0; i < userInp.size(); i++) {
switch (userInp[i])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
break;
default:
return false;
}
}
}
我只是尝试测试程序是否真的在字符串中进行迭代,而且确实如此,所以我不明白为什么在函数中它总是返回false?
int main() {
string userInp;
string pigLatin;
cout << "Please enter a string to convert to pig Latin: " << endl;
cin >> userInp;
cout << endl;
// tests
for (int i = 0; i < userInp.size(); i++) { //checking if it actually iterates
cout << userInp[i];
}
cout << endl;
if (scanStr(userInp))
cout << "it has a vowel" << endl;
else
cout << "no vowel" << endl;
system("pause");
return 0;
}
起初我以为是因为即使在最后一个情况之后有一个break语句,循环仍继续进行,但是我不确定这是否是原因。
有任何想法吗?
问题是,如果任何字符不是元音,则该函数立即返回false。也可以使用const &
。const
允许您传递const字符串,引用节省了一些时间,因为C ++不必复制整个字符串。
bool scanStr(const string & userInp) {
for (int i = 0; i < userInp.size(); i++) {
switch (userInp[i])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
return true;
break;
}
}
return false;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句