我需要做一个猜测的基本游戏,并且不知道如何循环代码,以便用户在遇到错误时再次输入他的答案。这是我写的整个代码:
#include <iostream>
#include <stdlib.h> //srand
#include <time.h> // time
#include <vector>
#include <stdexcept>
void error(std::string s)
{
throw std::runtime_error(s);
}
int main()
{
int characters ,length ,guess_number = 0,letter_number = 0, total_guess = 0 , err_count = 0;
char letters,guess;
std::vector <char> v;
std::vector <char> answer;
std::cout << "Enter the amount of different characters: ";
std::cin >> characters;
std::cout << "Enter the pattern length ";
std::cin >> length;
if(length > 26)
{
error("Length can't be over 26");
}
srand (time(NULL));
for(int i =0; i < length ; i++)
{
letters = rand()% (26-(26-characters))+65; //ascii code for Upper case letters. we discard the 26-characters to only generate random numbers up until how many characters.
letter_number++;
v.push_back(letters); //random letters
}
for(int i = 0;i <v.size(); i++)
std::cout << v[i];
try
{
while(guess_number != letter_number)
{
std::cout << "Enter your guess: ";
while(std::cin >> guess)
{
answer.push_back(guess); //user guess
if (std::cin.peek() == '\n')
break;
}
total_guess ++;
if(v.size() != answer.size())
{
error("Answer too short");
}
for(int i = 0; i < v.size(); i++)
{
if(v[i] == answer[i])
{
guess_number++;
}
}
if(guess_number != letter_number)
{
std::cout << "you have guessed " << guess_number << " characters correctly." << std::endl;
guess_number = 0;
answer = {};
}
else if(guess_number == letter_number)
{
std::cout << "You have guessed " << guess_number << " characters correctly" << std::endl;
std::cout << "You guesses the pattern in " << total_guess << " guesses";
break;
}
}
}
catch(std::runtime_error& error)
{
std::cerr << "error: "<< error.what() << std::endl;
return 1;
}
return 0;
}
基本上我不知道如果用户输入比随机字母向量更短的答案,如何让程序再次询问用户。在这部分之后:
if(v.size() != answer.size())
{
error("Answer too short");
}
在我运行它并输入一些简短的程序后,程序会给出错误并结束而不是再次运行。
答案 0 :(得分:0)
您的代码失败,因为一旦错误被触发,您就会捕获错误(在while
循环之外,基本上终止它),然后甚至执行return 1
(终止程序)。此外,由于错误可能会提前停止执行,因此您应始终在开始每个步骤后立即清除answer
。所以你应该做三件事:
try...catch
包裹在while
return 1
行,以便代码继续执行answer = {};
移至try...catch
看起来应该是这样的:
while(guess_number != letter_number)
{
try
{
answer = {};
std::cout << "Enter your guess: ";
while(std::cin >> guess)
{
answer.push_back(guess); //user guess
if (std::cin.peek() == '\n')
break;
}
total_guess ++;
if(v.size() != answer.size())
{
error("Answer too short");
}
for(int i = 0; i < v.size(); i++)
{
if(v[i] == answer[i])
{
guess_number++;
}
}
if(guess_number != letter_number)
{
std::cout << "you have guessed " << guess_number << " characters correctly." << std::endl;
guess_number = 0;
}
else if(guess_number == letter_number)
{
std::cout << "You have guessed " << guess_number << " characters correctly" << std::endl;
std::cout << "You guesses the pattern in " << total_guess << " guesses";
break;
}
}
catch(std::runtime_error& error)
{
std::cerr << "error: "<< error.what() << std::endl;
}
}
在这里:tio.run 注意:我将您的代码更改为始终&#34;生成&#34; AB作为模式