1

I made a simple game program, and a requirement calls for a option for the player to undo a number of moves (undo n).

I have the user enter in a command (undo n) and it takes the back half and puts it into an int. Basically, I want the program to stop the user if they entered in anything but a number. So if the user typed in undo f it won't convert f into it's number form (or at least that's what I think it would do) but it'll cause an error. I searched for a while and couldn't find anything that worked or made sense to me.

try {
   int undo;
   istringstream is(userInput.substr(5, userInput.length()));
   is >> undo;

   for (int numOfUndos = undo; numOfUndos > 0; numOfUndos--) {
      board.UndoLastMove();
   }
   moveValidated = true;
}
catch (exception &e) {
   cout << "/-----------------------------/" << endl;
   cout << e.what() << endl;
   cout << "/-----------------------------/" << endl;
}

If possible, I would like to just use how I currently have it or with cin. Also, forgive me, but I'm still learning C++ and don't know many advanced techniques, so if there is a complex way to do this forgive me if it takes me a bit to understand.

Thanks for any help in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Thomas Brooks
  • 49
  • 1
  • 3
  • The game description is not really relevent to your problem: how to convert a string into an integer and check if it failed. To do that, `if (is >> undo) { worked } else { failed }` Does UndoLastMove throw an exception? – Neil Kirk Nov 16 '14 at 23:01
  • FYI: If the input wasn't something that represented an integer (like alphabetical characters) then nothing is extracted into `undo`. `undo` will retain its uninitialized value and then the for loop will run, using that value, which is undefined behavior. This is why you should check your input with a conditional statement, like Neil Kirk shows. – David G Nov 16 '14 at 23:05
  • Yeah I saw that somewhere else, but I unfortunately left in the `is >> undo;` statement before the added conditional statement. I implemented it and it worked. Thanks. – Thomas Brooks Nov 17 '14 at 01:41

1 Answers1

0

This worked for me. Thanks again.

The game description is not really relevent to your problem: how to convert a string into an integer and check if it failed. To do that, if (is >> undo) { worked } else { failed } Does UndoLastMove throw an exception? – Neil Kirk

Thomas Brooks
  • 49
  • 1
  • 3