Way to detect number rather than letter from string. (using istringstream currently)

72 views Asked by At

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.

1

There are 1 answers

0
Thomas Brooks On

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