How to prevent the input from being any letters?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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? " ;
    const int row = get_int( 1, 3 ) ;
    std::cout << "you entered row #" << row << '\n' ;
}
Something like this:
1
2
3
4
5
6
7
8
9
    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
    }
Last edited on
JLBorges +1

Alternatively, for single-digit inputs, just get a character from the user:

1
2
3
4
5
6
7
8
9
10
11
  int n;
  while (true)
  {
    char c = cin.get();
    if ('1' <= c and c <= '3')
    {
      n = c - '0'; // n → [0,2]
      break;
    }
    cout << "Numbers, yo! Try again: ";
  }
Topic archived. No new replies allowed.