因此,我以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;
}
答案 0 :(得分:3)
#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;
}