2012-12-19 213 views
2

雙輸入,所以我想:麻煩與validaton C++程序

  1. 做一做裏面的雙輸入驗證while循環
  2. 檢查是否此舉尚未作出,是否有一個邏輯輸入。 (#1-9)

我原本以爲如果其他語句,但我不知道如何使用else語句返回到循環的開始。

do 
{ 
    cout << "Interesting move, What is your next choice?: "; 
    cin >> play; 
    Pused[1] = play; 
    if(play != Pused[0] && play != cantuse[0] && play != cantuse[1]) 
    { 
    switch(play) 
    { 
     default:cout << "Your choice is incorrect\n\n"; 
     break; 
    } 
    } 
    else 
    { } 
}  
while(play != 1 && play != 2 && play != 3 && play != 4 && play != 5 && play != 6 && play != 7 && play != 8 && play != 9); 
Dis_board(board); 
+4

請你的代碼減少到最低限度,如果你希望人們讀它 –

回答

0

使用「continue」關鍵字返回循環開始。

+0

它是一個DO WHILE和,因爲它是真實的,num是1-9退出....它不檢查看看1-9是否已經輸入 – user1914650

0

剛刪除else。我認爲這不是必需的。如果條件滿足while,自動循環將繼續。

+0

它需要其他的,因爲如果是說如果它沒有進入他們做功能,否則.....我需要其他返回到if語句之上。 ......如果可能的話......或者如果可能的話,發給Do語句...... – user1914650

+0

如果你想在別的地方做一些操作,那麼只有其他的地方是必需的。如果你的遊戲值超過9,那麼循環將繼續,否則它會出來。此外,您可以使用while(!(play> 9))作爲條件檢查,而不是寫入很大的while循環條件。 – Nipun

0

你的問題是有點難以理解,但你有幾個條件,在這個循環來解決:

  1. 詢問用戶輸入
  2. 檢查用戶輸入有效(間1-9而不是之前)
  3. 退出循環使用了,如果我們有一個有效的選擇

所以我們需要記錄動作已經做了什麼,並檢查用戶的輸入是有效的選擇中,我們可以使用僅在選擇有效選擇時退出的循環。

int choice; 
bool used[9] = { false }; // Set all values to false 
std::cout << "Interesting move, what is your next choice?: "; 
do { 
    std::cin >> choice; 
    // Here we check if the choice is within the range we care about 
    // and not used, note if the first condition isn't true then 
    // the second condition won't be evaluated, so if choice is 11 
    // we won't check used[10] because the && will short circuit, this 
    // lets us avoid array out of bounds. We also need to 
    // offset the choice by 1 for the array because arrays in C++ 
    // are indexed from 0 so used runs from used[0] to used[8] 
    if((choice >= 1 && choice <= 9) && !used[choice - 1]) { 
     // If we're here we have a valid choice, mark it as used 
     // and leave the loop 
     used[choice - 1] = true; 
     break; // Exit the loop regardless of the while condition 
    } 

    // If we've made it here it means the above if failed and we have 
    // an invalid choice. Restart the loop! 
    std::cout << "\nInvalid choice! Input: "; 
} while (true);