There is a code:

char field[3][3]; void enterX() { cout << "Enter X on vertical: "; int i; cin >> i; if (cin.good() && i < 3 && i >= 0) { } else { cout << "Please, enter the number 0-2!"; cin.clear(); cin.ignore(INT_MAX); enterX(); } cout << "Enter X on horizontal: "; int j; cin >> j; if (cin.good() && j < 3 && j >= 0) { } else { cout << "Please, enter the number 0-2!"; cin.clear(); cin.ignore(INT_MAX); enterX(); } field[i][j] = 'x'; } 

The task is to read the number of the array element from the console and insert the 'x' character in this place. However, if entered incorrectly, recursion does not occur. What is the problem?

  • one
    See what the debugger is doing. - Vladimir Martyanov

1 answer 1

Actually, this is cin.ignore(INT_MAX); - ignore everything (ok, INT_MAX characters) until the end of the file - i.e. until some ^ Z closes the stream ...

 input.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

And in general, I would do this (if it is precisely the recursion that wears):

 char field[3][3]; void enterX() { cout << "Enter X && Y: "; unsigned int i, j; cin >> i >> j; if (cin.fail() || i > 2 || j > 2) { cin.clear(); cin.ignore(INT_MAX,'\n'); cout << "Wrong values!\n"; enterX(); } else { field[i][j] = 'x'; } } 

Update

Having typical terminal recursion, it is better to convert it into an iteration:

 char field[3][3]; void enterX() { for(;;) { cout << "Enter X && Y: "; unsigned int i, j; cin >> i >> j; if (!(cin.fail() || i > 2 || j > 2)) { field[i][j] = 'x'; break; } cin.clear(); cin.ignore(INT_MAX,'\n'); cout << "Wrong values!\n"; } } 
  • But eternal recursion occurs without it - Sergei Mikhailovskii
  • You do it all crooked. If you even entered the first number normally, and the second is incorrect - the recursion will begin to require the input of the first number ... And I wrote to you - add the second parameter '\n' , but do not remove at all! - Harry
  • See updated reply - Harry
  • And what options without recursion? - Sergei Mikhailovskii
  • Iteration, of course. - Harry