tags:

views:

62

answers:

1

Example user input:

PA1 9 //correct 
PJ1 9 //wrong, error printed "Invalid row" because it is not between A and I 
PA11 9 //wrong, error printer "Invalid column" because it is not between 1 and 9.

The problem I am having is that it should clear the remaining input and then ask for the user to enter the "move" again, and it is not.

Where did I go wrong? I've been at it for a while and still got no progress..

void clearInput()
{ 
 cin.clear();
}

bool getCoords(int & x, int & y)
{
 char row;

 while(true){
 cin>>row>>y;
 row=toupper(row);

 if(/*(id=='P' || id=='p' || id=='D' || id=='d') &&  */row>='A' && row<='I' && isalpha(row)  && y>=1 && y<=9){ 
     x=row-'A';
  y=y-1; 
  return true;
 }

 else if(!(y>=1 && y<=9)){
  cout<<"Invalid column\n"<< endl << endl;
  cout<<y;
  clearInput();
  cout<<y;
  //return false; 
 }
 else{
  cout<<"Invalid row\n"<< endl << endl;
  clearInput(); 
  //cout<<x<<y;
  //return false;
 }
 }
}
+1  A: 

cin's clear member function doesn't clear the remaining input, it resets the error flags on the stream (which could get set e.g. because you tried to read an integer but there were non-digit characters in the input). I guess you really want to discard the input up to the next newline; one way to do this would be to call cin.ignore with '\n' as the delimiter.

Another thing that could be an issue (but might just be code left out in the question ;)) is that the while(true) loop that you've written to repeatedly ask for input until there's no error doesn't contain the board-redrawing logic you talk about in your comment. So you won't see this until the getCoords function finds error-free input and returns.

Mike Dinsdale
Ah, yes I figured that was part of the problem..
codefail