2013-03-19 198 views
0

我想讓它如此,如果用戶輸入一個數字少於4或更大他們10他們被提示它是無效的,並輸入一個新的數字。我遇到的問題是,如果他們輸入正確的號碼,它不會繼續到下一部分。這是我到目前爲止:C++做while循環與用戶輸入

#include <iostream> 
#include <iomanip> 
#include <string> 
#include <fstream> 
#include <cstdlib> 
#include <ctime> 

int NewRandomNumber (int n); 
void MakeQuestion (int n, int& a, int& b, int& atimesb); 
bool UserAnswer (int a, int b, int atimesb); 
void PrintScore (int numCorrect, int numAsked); 

using namespace std; 

int main() 

{ 
string name; 
int n; 
string s; 




cout << "Welcome to Multiplication Quiz 1000!" << endl; 
cout << "Firstly what is your name?\n" << endl; 

cin >> name; 

cout << "\nHi " << name <<" !" << endl; 
cout << "What difficulty would you like your quiz to be? Enter a value from [4 to 12] 

     \nwith 4 being the easiest:\n" << endl; 

do 
{ 
cin >> s; 
n = atoi(s.c_str()); 

if (n >= 4 || n <= 10) 



    if (n < 4 || n > 10) 
    {cout << "invalid. try again" << endl; 
    } 



{cout << "Ok" << endl; 
cout << NewRandomNumber (4); 
} 

} 
while (n >= 4 || n <= 10); 


return 0; 

} 

int NewRandomNumber (int n) 

{ 

    n = rand()% 10 + 1; 




return (n); 

} 

void MakeQuestion (int n, int& a, int& b, int& atimesb) 

{ 
} 
+0

使用getline而不是從鍵盤getline(cin,s)讀取; – 2013-08-15 12:28:20

回答

1

我想你錯過了繼續聲明。

// ............. 

     if (n < 4 || n > 10) 
      {cout << "invalid. try again" << endl; 
      continue; 
      } 

    //.............. 
1

嘗試通過使用一個標誌是這樣的:

int flag=0; 

do{ 

cin >> s; 
n = atoi(s.c_str()); 


if (n < 4 || n > 10) 
{ 
    cout << "invalid. try again"; 
} 
else 
{ 
    flag=1; 
    cout<<"OK" 
} 
}while(flag=0); 

它已經相當一段時間,因爲我在C++編程了,所以有可能會出現一些小問題與語法。但是這裏的邏輯應該沒問題。

4

您的while(n >= 4 || n <= 10)條件將始終爲真。你應該去while (n <= 4 || n >= 10)

有幾種方法可以解決您的問題,就像它已經發布在這裏一樣。我會用一個continue聲明,像懶鬼說的,但一定要改變你的,而的條件,否則它就失去了工作。它會是這樣的:

while (true) { 
    cin >> s; 
    n = atoi(s.c_str()); 

    if (n <= 4 || n >= 10) { 
    // handles your exception and goes back to the beggining of the loop 
    continue; 
    } 
    else { 
    // the number was correct, so make your magic happen and then... 
    break; 
    } 
}