我正在寫一些代碼,並遇到了一些麻煩。我想寫一個函數來檢查一個字符串是否有元音,並試圖通過一個帶有switch語句的for循環來實現。顯然,它不起作用,並且由於某種原因從不返回真實。迭代通過一個字符串,並切換語句:C++
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語句,但我不能完全肯定,如果這就是原因所在。
任何想法?
您的代碼是錯誤的。我會爲你修復它 – tomascapek
你的循環計數器'i'應該是'std :: size_t'類型,因爲'userInp.size()'可能並不總是符合簽名的'int'。 – jotik
另請注意,'return true;'語句後面的'break;'語句是死代碼,並且永遠不會執行。 – jotik