簡體   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