我被困在学校的随机猜谜游戏中。
我添加了需要添加的代码,但控制台会在不返回最后一个字符串的情况下保持关闭状态。
我还想了解如何再次运行该程序,点击Y
再次运行。
我还在学习C ++,所以任何帮助都会受到赞赏。
代码:
// GuessingGameApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>//added to run string
#include <locale>//added toupper run again
using namespace std;
int main()
{
//Seed the random number generator
srand(time(0));
int selectedNumber = rand() % 20 + 1; int numberOfTries = 0;
int inputtedGuess;
std::cout << "Guess My Number Game\n\n";
//Ask the user for a value until the correct number is entered
do {
std::cout << "Enter a guess between 1 and 20:";
std::cin >> inputtedGuess;
++numberOfTries;
if (inputtedGuess > 20 || inputtedGuess < 1) {
cout << "Your guess is out of range.\n\n";
}
else if (inputtedGuess > selectedNumber) {
cout << "Too high!\n\n";
}
else if (inputtedGuess < selectedNumber) {
cout << "Too low!\n\n";
}
}
while (inputtedGuess != selectedNumber);
//Congratulate the user and end the program
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" << std::endl;
//fix problem with console closing and (add "play again" option), so I can
//learn
//printf; did not work... Break did not work..
//
return 0;
}
我可以通过在第33行添加break
来让控制台保持打开状态,但我想学习如何正确执行此操作,因此我删除了break
。
答案 0 :(得分:1)
实际上应该打印输出的最后一行。最后一行&#34;没有打印的原因&#34;可能是你的IDE在你看到最终输出之前关闭了控制台(尽管它应该在那里)。许多IDE允许在程序终止后使控制台可见。顺便说一句:请注意,在粘贴代码时,您可能会在<<
std::endl
之前丢失std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl;
但这实际上是一个复制粘贴问题,因为您的程序不会编译。
无论如何,通过提供&#34;再试一次?&#34; -logic,您的程序不会终止并且问题就解决了。
我建议提供一个执行猜测的单独函数,然后在带有"Try again="
- 问题的do-while循环中调用。
void guess() {
// your code (except srand) goes here...
}
int main() {
srand(time(0)); //Seed the random number generator only once
char doAgain;
do {
guess();
cout << "Try again (Y/N)?";
cin >> doAgain;
}
while (toupper(doAgain)=='Y');
return 0;
}
答案 1 :(得分:0)
正如人们建议的那样,你可以添加另一个do-while循环来重复游戏。
int choice = 0;
do {
// first part of code..
do {
// inner do-while
} while (inputtedGuess != selectedNumber);
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl;
cout << "\nWould you like to play again?\n\n";
cout << "1 - Yes\n";
cout << "2 - No\n\n";
cout << "Choice: ";
cin >> choice;
} while(choice == 1);