繁体   English   中英

C ++做while循环与用户输入

[英]c++ do while loop with user input

我正在尝试这样做,以便如果用户输入的数字小于4或大于10,则提示他们无效并输入新的数字。 我遇到的问题是,如果他们输入正确的数字,它将无法继续进行下一部分。 这是我到目前为止的内容:

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

{
}

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

有几种方法可以解决您的问题,就像已经在此处发布的一样。 我会像slacker所说的那样continue声明,但是一定要更改while条件,否则它将无法正常工作。 就像这样:

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;
    }
} 

我想你想念继续声明。

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

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

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

通过使用标志来尝试这种方式:

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 ++编程以来已经有一段时间了,因此语法可能存在一些小问题。 但是这里的逻辑应该没问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM