2014-09-13 64 views
0

我試圖模仿一個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; 
} 
+1

http://stackoverflow.com/questions/8146106/does-case-switch-work-like-this將幫助您簡化您的代碼。 – 2014-09-13 14:03:46

回答

2

您可以像讀取行本身一樣閱讀行數。

string totalstring; 
getline(cin, totalstring);  
total = stoi(totalstring); 

這樣,換行符將被消耗。

+0

我在哪裏添加?另外stoi做什麼? – jarkia 2014-09-13 14:27:53

+0

你可以用這個替換'cin >> total;'。 'stoi'只是字符串到整數。 – broncoAbierto 2014-09-13 15:43:06