I'm coding a Tic Tac Toe program for school, and I'm having a problem where if the input is something else that ISN'T a number, my code goes on this crazy loop. Here's the function in question
void playerTurn(char test[][4],int player)
{
int row1;
int col1;
do
{
do
{
cout<<"Player ";
cout<<player+1 << ", Row: ";
cin >> row1;
}
while(row1 < 1 || row1 > 3 && !(row1<='A'&&row1>='Z') && !(row1<'a'&&row1>'z')); ///My attempt at a fix
do
{
cout<<"Player ";
cout<<player+1 << ", Column: ";
cin >> col1;
}
while(col1 < 1 || col1 > 3); ///It's also gonna go here
}
while(test[row1][col1]=='X'||test[row1][col1]=='O');
if (player==0)
{
test[row1][col1]='X';
}
else
{
test[row1][col1]='O';
}
}
Notes: The char array in question is defined as Char test[4][4]
(Also, please no "std::whatever" solutions. We haven't covered that yet :) )
Any idea how to ban use of anything besides numbers? Thanks!
#include <iostream>
int get_int( int minv, int maxv )
{
std::cout << "enter an integer in the interval [" << minv << ',' << maxv << "]: " ;
int value ;
if( std::cin >> value ) // if a number was read successfully
{
// return the value if it is within the valid range
if( value >= minv && value <= maxv ) return value ;
else std::cout << value << " is out of range. " ;
}
else // if input failed (user entered invalid characters)
{
std::cout << "invalid character in input. " ;
std::cin.clear() ; // clear the failed state of the stream
std::cin.ignore( 1000, '\n' ) ; // and throw the input away
}
std::cout << "try again\n" ;
return get_int( minv, maxv ) ;
}
int main()
{
std::cout << "row? " ;
constint row = get_int( 1, 3 ) ;
std::cout << "you entered row #" << row << '\n' ;
}
int row1;
// cin >> row1; // replace this line
while (!(cin >> row1)) // get input and test if ok
{
cin.clear(); // reset status flags
cin.ignore(1000, '\n'); // remove unwanted characters from buffer
}