簡體   English   中英

如何使用遞歸來循環我的代碼(當用戶輸入無效輸入時,它會再次提示它們)?

[英]How do I use recursion to loop my code (when user enters invalid input, it prompts them again)?

所以我用C ++格式編寫了這段代碼,我試圖循環代碼,當用戶輸入無效輸入時,當提示輸入1到10之間的數字時,它不會在無效輸入時終止,而是要求用戶輸入有效輸入,直到輸入有效輸入。 c ++的新手,所以我很感激幫助

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>

using namespace std;

//constants go here
const int MIN = 1;
const int MAX = 10;

const char YES = 'Y';
const char NO = 'N';

//Booleans go here
char wantToPlay();
bool getIntValue(int &userValue);
bool play(int userValue);

//Main routine
int main(){

printf("Welcome, this program will guess a number between 1 and 10");
printf(", if the program guesses the number correctly you'll get VICTORY ROYALE");
printf(", if you don't get it right you'll get BETTER LUCK NEXT TIME, Good luck :)\n");

char playOrNot = wantToPlay();

  //If user value is TRUE, program outputs "Victory Royale" and terminates
  //If user value is FALSE, program outputs "Better luck next time" and terminates
  //If user value is NOT VALID, program outputs "Not a good number" and prompts user again
  //If user enters "N" when prompted to answer Y or N
  int input = -1;
  switch (playOrNot){
  case YES:
    if(getIntValue(input)){
      srand (time(NULL));
      if(play(input)){
    cout << "Victory Royale!"<<endl;
    }else{
    cout<<"Better Luck Next Time!"<<endl;
    }
    }else{
      cout<<"not a good number\n";
    }
    break;
  case NO:
    cout << "sorry you hate my game\n";
    break;

  default:
    cout << "that was not valid\n";
    //If user enters value that is completely not valid
  }


  return 0;
}
char wantToPlay(){
  //Prompt user to enter Y for yes and N for no
  char answer = NO;
  cout << "Do you Want to Play? 'y'for" << " yes, 'n' for no" << endl;
  cin >> answer;
  answer = toupper(answer);
  return answer;
}


bool getIntValue(int &userValue){
  //Prompt user to enter a number between the Min(1) and Max(10)
  bool valid = false;
  cout <<"Enter a number between " << MIN << " and " << MAX <<endl;
  cin>>userValue;
  if(userValue >= MIN && userValue <= MAX){
    valid = true;
  }


  return valid;
}
bool play(int userValue){
  //Random tool to give a random between 1 and 10
  bool match = false;
  int random = (rand()%10)+1;
  if(userValue==random){
    match=true;
  }
  return match;
}
#include<iostream>
using namespace std;
int main()
{
    char s;
    cout<<"Enter valid number between 1 to 10"<<endl;
    cin>>s;
    while(!((s>='1') && (s<='10')))
    {
        cout<<"The number you have entered is not in range 1 - 10"<<endl;
        cout<<"Enter an valid number I.e. between 1 to 10"<<endl;
        cin>>s;
    }
    cout<<"You have successfully entered an valid number"<<endl;
    return;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM