c ++使用用户输入执行while循环

时间:2013-03-19 03:43:32

标签: c++ cin

我试图这样做,如果用户输入的数字小于4或更大,则会提示它们无效并输入新号码。我遇到的问题是,如果他们确实输入了一个正确的数字,它就不会继续下一部分。以下是我到目前为止的情况:

#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)

{
}

3 个答案:

答案 0 :(得分:4)

您的while( n >= 4 || n <= 10)条件始终为真。你应该使用while (n <= 4 || n >= 10)

有几种方法可以解决您的问题,就像它已经发布在这里一样。像slacker说的那样,我会使用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;
    }
} 

答案 1 :(得分:1)

我想你错过了继续声明。

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

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

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

答案 2 :(得分: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 ++编程以来已经有一段时间了,所以语法可能会有一些小问题。但这里的逻辑应该没问题。