2017-07-08 70 views
-4

試圖創建我的第一個項目預期的行爲:代碼不會口出while循環

1. User inputs an integer (lets say 7) 
2. User continues to input same integer more times (lets say 4 total) 
3. User inputs 8 
4. Program then prints ("the count of 7 was 4") 
5. User continues to enter 8 (lets say a 8 was entered a total of 11 times) 
6. User enters 73 
7. Program then prints ("the count of 8 was 11") 

後第4步,程序卡住任何投入一代產量「7進0次」

#include <iostream> 

int main(){ 

    int inputtedvalue = 0; 
    int firstvalue = 0; 
    int cnt = 0; 

    if(std::cin >> firstvalue){ 
     ++cnt; 
     while(std::cin >> inputtedvalue){ 
      if(inputtedvalue == firstvalue) 
       ++cnt; 
      else{ 

       std::cout << "the count of " << firstvalue <<" is " << cnt << std::endl; 
       inputtedvalue = firstvalue; 
       cnt= 1; 
      } 
     } 
    } 
} 
+1

您的意思是'firstvalue = inputsvalue;'? – melpomene

+5

這是一個很好的例子,說明命名選項的糟糕程度如何難以調試。如果'firstvalue'被命名爲'currentvalue',那麼分配意外顛倒就更爲明顯了。 – druckermanly

+0

這是[mcve]嗎?我看不出任何可能導致輸出「7被輸入0次」的代碼。 – Yunnosch

回答

0

我在看你的例子,我相信以下可能會讓你回到正確的方向。

using namespace std; 

int main(){ 

int inputtedvalue = 0; 
int firstvalue = 0; 
int cnt = 0; 

cout << "Enter Starting value."<< std::endl; 
if (cin >> firstvalue){ 

    cout << "New count " << firstvalue <<" of " << cnt << endl; 
    while(cin >> inputtedvalue) 
    { 
     if(inputtedvalue != firstvalue) 
     { 
      cout << "It Doesn't Match" << endl; 
      firstvalue = inputtedvalue; 
     } 
     else 
     { 
      cout << "It Matches" << endl; 

     } 
    } 
}