2014-02-19 90 views
0

我想做一個函數來確保一個數字大於零,但是隻要用戶沒有輸入大於零的數字,他們就必須在代碼繼續之前輸入一個值兩次。請幫忙!Cin需要2個輸入

int userInput() 
{ 
    int goAhead = 0; 
    int a; 

    while (goAhead == 0) 
    { 
     cin >> a; 
     if(a <= 0) 
     { 
      cout << "The can not be less than or equal to zero, enter another value: " << endl; 
      cin >> a; 
      cin.ignore(); 
     } 
     else 
     { 
      // enter code here 
      goAhead = 1; 
     } 
     return a; 
    } 
} 
+0

它不是明確 – aah134

回答

0

我希望它能幫助:

int userInput() 
    { 
     int a = 0; 
     while(a <= 0) { 
      cout << "Enter value greater than zero: " << endl; 
      cin >> a ; 
      if(a <= 0) 
       cout << "Input incorrect. Please try again " << endl; 
     } 
     return a; 
    } 
+1

迂挑剔:此代碼是一個無限循環如果流進入一個壞/故障狀態。乾淨地修復是棘手的,但我不會推薦給新手。 –

+0

謝謝!我對C++非常陌生,所以我把所有事情都做得比它應該更復雜。我不明白爲什麼原始代碼有小錯誤。哦,謝謝你! – user3329737

+0

@ user3329737:使用調試程序瀏覽代碼,即使對於新手也應該​​立即顯而易見。 –

0
int userInput() 
    { 
     int a; 
     int tries = 2; // this will count down to 0, which then return anything you want as an invalid answer 

     do 
     { 
      cout << "enter value: "; 
      cin >> a; 

      if(a > 0) 
      { 
       return a; 
      } 
      else 
      { 
       if(--tries > 0) 
       { 
        cout << "The can not be less than or equal to zero" << endl; 
       } 
       else 
       { 
        cout << "returning -1" << endl; 
        return -1; 
       } 
      } 
     }while (true); 
    } 
0

嘗試使用while循環

cin>>a; 
while(a<=0) 
{ 
System.out.println("Please enter again"); 
cin>>a; 
} 

,如果你只想要2次以上,只需添加一個計數器。

我希望它有幫助。

0

這應該做你正在嘗試

int userInput() 
{ 
    int a; 
    cin >> a; 
    while(a <= 0) 
    { 
     cout << "The can not be less than or equal to zero, enter another value: "<< endl; 
     cin >> a; 
     cin.ignore(); 
    } 
    return a; 
}