我正在编写一些代码,遇到了一些麻烦。我想编写一个函数来检查字符串是否有任何元音字母,并尝试通过for循环和内部的switch语句来实现。显然,它不起作用,并且出于某种原因从未返回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;
}
一开始我以为是因为在最后一个case之后有一个break语句,但循环仍然继续执行,但我不确定这是否是原因。
有什么想法吗?
i
应该是std::size_t
类型,因为userInp.size()
可能不适合有符号的int
。 - jotikreturn true;
语句后面的break;
语句是死代码,永远不会被执行。 - jotikstd::string::find_first_of
的内容。 - Pete Becker