【发布时间】:2021-06-21 22:04:39
【问题描述】:
这是我的第一个堆栈溢出问题,所以如果我不是描述性的,请多多包涵。我的任务是创建一个非常简单的基于点数系统的骰子程序,例如如果你落在 1-12 的特定数字上,你要么赢一分,要么输。基本上就是这样。我的问题是,我应该放置一个验证函数,以防用户输入错误的输入。我让程序仅在用户输入“y”或“n”时运行,如果没有,它会提示用户输入正确的响应。
class Game
{
private:
int die1;
int die2;
int dice;
int totalPoints;
int totalRolls;
char ch;
void prompt();
void display();
void validate();
void rolls();
public:
void driver();
Game();
};
int main()
{
Game dcObj;
dcObj.driver();
cout << "\n\n\n\n\n\n";
return 0;
}
Game::Game()
{
totalPoints = 0;
totalRolls = 0;
srand(time(NULL));
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
dice = die1 + die2;
}
void Game::driver()
{
prompt();
display();
}
void Game::display()
{
cout << "\n\nYou rolled the dice " << totalRolls << " times.";
cout << "\nYou won " << totalPoints << " points.";
if (totalPoints <= 0)
{
cout << "\n\nBetter luck next time!";
}
else
cout << "Not bad!";
}
void Game::prompt()
{
cout << "\nWelcome To My Game of Absolute Chance!";
cout << "\n\nDo you want to roll? (y = yes, n = no) ";
cin >> ch;
validate();
}
void Game::validate()
{
while (ch != 'n' || ch != 'y')
{
fseek(stdin, 0, SEEK_END);
cin.clear();
cout << "Invalid response. Please input (y = yes, n = no) ";
cin >> ch;
}
}
void Game::rolls()
{
while (ch == 'y')
{
switch(dice)
{
case 2: cout << "Sorry, you rolled a " << dice << ", you lost.";
totalPoints--;
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 3: cout << "Sorry, you rolled a " << dice << ", you lost.";
totalPoints--;
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 4: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 5: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 6: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 7: cout << "Congratulations! You rolled a " << dice << ", you win!";
totalPoints++;
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 8: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 9: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 10: cout << "You rolled a " << dice << ", you get nothing.";
totalRolls++;
cout << "Points: " << totalPoints;
break;
case 11: cout << "Congratulations! You rolled a " << dice << ", you win!";
totalPoints++;
totalRolls++;
break;
case 12: cout << "Sorry, you rolled a << " << dice << ", you lose.";
totalPoints--;
totalRolls++;
break;
}
}
if (ch == 'n')
{
display();
}
}
我的问题是,无论输入是否良好,while 循环总是会运行。输入“y”或“n”仍会使其运行。我几乎尝试了所有事情。任何帮助都会很棒!
【问题讨论】:
-
ch 是成员变量吗?可以分享一下完整代码吗?
-
@DebojyotiMajumder 编辑了它。代码比较多,但剩下的代码是一个开关函数,将每个数字分配给积分系统
-
你应该把所有的代码都放好,以便我们重现它。
-
@TudorTeo 整个代码都起来了!
-
每个字符不是
n或不是y。 “不是n或不是y”可能为假的唯一方法是如果某事物既是n又是y,这是不可能的。
标签: c++ validation input while-loop