2014-10-27 54 views
0
std::cout << "How many turns do you want to do?" << std::endl << std::endl << std::endl; 
    std::string turnsDefined; 
    std::cin >> turnsDefined; 
    //std::cin.sync(); 
    bool hasPassed = false; 
    int objectSizeIniti = 0; 
    int objectSizePost = 0; 
    for(char c : turnsDefined){ 
     objectSizeIniti++; 
    } 
    bool boolForCharIsDigi[objectSizeIniti]; 
    for(bool _b : boolForCharIsDigi){ 
     _b = false; 
    } 

while(hasPassed != true){ 
     for(char c : turnsDefined){ 
      if(isdigit(c) == 0){ 
       boolForCharIsDigi[objectSizePost] = false; 
      }else if (isdigit(c) != 0){ 
       boolForCharIsDigi[objectSizePost] = true; 
      } 
      bool allTrue = false; 
      for(int i = 0; i < sizeof(boolForCharIsDigi)/sizeof(boolForCharIsDigi[0]); i++){ 
       if(boolForCharIsDigi[i] == false){ 
        allTrue = false; 
        std::cin >> turnsDefined; 
        std::cout << "You may only use numbers to define the amount of turns. No decimals either." << std::endl << std::endl; 
        break; 
       }else if(boolForCharIsDigi[i] == true){ 
        allTrue = true; 
        hasPassed = true 
       } 
      } 
     } 
     objectSizePost++; 
    } 

我想理解爲什麼上面的代碼行爲如此奇怪。奇怪的循環邏輯在c + +

我想要做的事:

,我發現了輸入和測試,如果它僅由數字組成。如果是這樣,它只是通過循環(將w循環檢查的變量設置爲true)。如果輸入確實包含數字以外的字符,它會請求另一個輸入並警告用戶。

發生了什麼:它隨機需要一些輸入來實際接受「唯一數字」。整體而言,整個項目只是隨機行動。

+1

你嘗試調試它以檢查問題?如果您嘗試逐步調試,則可以輕鬆找到問題的原因。 – Jepessen 2014-10-27 17:18:32

+0

'while(hasPassed!= true)'讓我變得很溫順。 – 2014-10-27 17:22:51

+0

@Jepessen這就是我所做的。沒有幫助,雖然我根本無法弄清楚邏輯。它迭代真的很奇怪... – Code0 2014-10-27 17:26:40

回答

3

我在做什麼: 我得到的輸入和測試,如果它只包含數字。如果它 確實如此,它只是通過循環(設置變量w循環 檢查爲真)。如果輸入確實包含 數字以外的字符,它會請求另一個輸入並警告用戶。

跳過調試部分,我建議你應該有std::all_of

if(std::all_of(turnsDefined.begin(), turnsDefined.end(), ::isdigit)) 
{ 
    // Correct input 
} 

else 
{ 
    // Warn the user, re-enter stuff 
} 
+0

我真的很感謝你的(工作)答案。不過,我也想知道我在原始代碼中做了什麼錯誤。 – Code0 2014-10-27 17:49:17

2

在代碼中,for循環初始化 'boolForCharIsDigi' 永遠不會更新實際的數組:

for(bool _b : boolForCharIsDigi){ 
    _b = false; 
} 

問題是_b是一個臨時變量。你需要使它像這樣的引用:

for(bool& _b : boolForCharIsDigi){ 
    _b = false; 
} 

可能有其他的問題,但是這一次跳進我的眼睛.. ;-)