This is a portion of my code for a game. If the user enters a number > 9 it does cout the response however it just keeps going. It does not stop the program and allow the user to re enter the number. My question is how do I allow the user to re enter the number whenever they enter the wrong thing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{
if ( number <= 9) //
{
cout << "That number works. Next player" << endl;
return 1;
}
elseif (num1 > 9);
{
cout << "That number is invalid. Please make sure you enter a number between 1 and 9" << endl;
return 0;
}
}
Also is there a way for me to stop the user from entering the same number twice without using a vector. For example if the user enters 9 and then then they enter 9 again it will cout something like " you entered that number already" and then allow them to enter a different number.
Hope I was clear enough thank you in advance.
while (number > 9){
cout << "That number is invalid. Please make sure you enter a number between 1 and 9" << endl;
}
cout << "That number works. Next player" << endl;
return 1;
player 1 pick your number
10
That number is invalid. Please make sure you enter a number between 1 and 9
0 | 1 | 10
------------
9| 2 | 8
------------
6 | 3| 7
No winner yet! Next player
Player 2 pick your spot! (x,y)
Used the while loop @McNo but it still keeps playing after it states the number is invalid
And switch your bool validate (int number) function to the way you had it before:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{
if ( number <= 9) //
{
cout << "That number works. Next player" << endl;
return 1;
}
elseif (num1 > 9);
{
cout << "That number is invalid. Please make sure you enter a number between 1 and 9" << endl;
return 0;
}
}
This way the user must enter a valid input before your program continues.
// I used doubles so it works for both int and double values
bool Validate(double value, double low, double high)
{
if(value < low || value > high) return 0;
return 1;
}
void GetInput(const std::string& prompt, int& value)
{
while(std::cout << prompt << ": ", std::cin >> value)
{
if(Validate(value,1,9)) return;
}
std::cout << "Error: Wrong data type or failure on stdin!";
}
int main()
{
int i;
GetInput("Enter a number between 1 and 9",i);
std::cout << "You entered << i << "\n";
}
The code that i showed was only for one of my .cpp files I thought I could make it work by only editing my bool validate function. I'll try to implement what you said though.