Я почти закончил работу над маленькой гадательной игрой, но у меня возникла проблема, я не знаю, как работать.C++ Функция вызывается, когда она не предполагается
Проблема с функцией check_guess, что проверка, чтобы убедиться, что догадка на вход представляет собой число от 1 до 100.
при запуске программы в первый раз, все работает отлично.
http://i.imgur.com/pprunDT.png (я бы разместить изображения, если моя репутация не были настолько низкими)
Но каждый раз после того, как, где да играть снова выбирается, программа запускается с помощью функции check_guess и отображает «Invalid Input», когда он не должен
http://i.imgur.com/8OSnSJt.png
Я не уверен, почему программа ведет себя таким образом.
Код для всей программы здесь:
#include <iostream>
#include <cstdlib> //for rand
#include <ctime> //for time
#include <string>
#include <sstream> //for conversions from string to int
using namespace std;
int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if (!(convert >> result) || (result < 1 || result > 100)) {
result = 0;
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
cin >> yn;
if (yn == "y" || yn == "yes") {
quit = false;
}
else if (yn == "n" || yn == "no") {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while (yn == "invalid");
return quit;
}
int main()
{
srand(time(0)); //sets seed to be random
int mystery = 0; //defines mystery number
int guess = 0; //defines guess
int tries = 5; //defines trys
bool quit = false; //defines replay or quit
cout << "----------------------------------\n";
do { //while mode is not set to quit, keep playing
tries = 5; //resets tries each new game
mystery = rand() % 100 + 1; //sets mystery number to be random
guess = 0;
cout << "Pick a number between 1 and 100.\n\nYou have 5 tries: ";
while (tries != 0) { //loops until you have no tries left
guess = check_guess(tries);
if (guess == mystery) { tries = 0; } //if you guess right it ends the loop
else { tries--; } //guessing wrong lowers tries by 1
if (tries != 0 && guess > mystery) {
cout << guess << " is too high.\n" << endl;
cout << "You have " << tries << " tries: ";
}
if (tries != 0 && guess < mystery) {
cout << guess << " is too low.\n" << endl;
cout << "You have " << tries << " tries: ";
}
}
if (guess == mystery) { //if guess == mystery by time loop ends you win
cout << "Got it! You Win!\n" << endl;
}
else { //if not, you lose
cout << "You Lose! The number was: " << mystery << ".\n" <<endl;
}
cout << "-------------------\n";
cout << "Play Again?(y/n): "; //ask user to play again
quit = play_again();
cout << "-------------------\n";
if (quit == false)
cout << endl;
} while (quit == false);
cout << "----------------------------------" << endl;
return 0;
}
Я не уверен, как это исправить.
Вы, вероятно, следует сделать несколько простых отладку, чтобы увидеть, если условия для вашего '' если ((конвертировать >> результат) || (результат <1 || результат! > 100) '' утверждение - это то, что вы ожидаете от них. Это приведет вас к проблеме довольно быстро, я ожидаю. – aruisdante
не то, что «конец строки» после ответа «y» от «Играть снова?» (y/n): «вопрос?» Это приводит к пустой строке при первом просмотре номера. –