我試圖模仿一個while循環來計算設定行數中的元音。第一個輸入是要輸入的總行數。然而,這會啓動循環並輸出一個0.這意味着它只能計算7行而不是8個。我可以通過將count設置爲-1來解決此問題,但它仍然會輸出隨機零。有沒有辦法可以改變循環來解決這個問題?C++雖然循環啓動得太早
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string sentence;
int count;
int total;
int length;
int lengthcount;
int output;
output = 0;
length = 0;
count = 0;
total = 0;
lengthcount = 0;
cin >> total;
while (total != count){
getline(cin, sentence);
length = sentence.length();
while (length != lengthcount){
switch(sentence[lengthcount]){
case 'a':
++output;
break;
case 'e':
++output;
break;
case 'i':
++output;
break;
case 'o':
++output;
break;
case 'u':
++output;
break;
case 'y':
++output;
break;
}
++lengthcount;
}
cout << output << " ";
++count;
lengthcount = 0;
output = 0;
}
return 0;
}
http://stackoverflow.com/questions/8146106/does-case-switch-work-like-this將幫助您簡化您的代碼。 – 2014-09-13 14:03:46