Hello everyone,
I trying to make a game in C++ right now and I want to make it so when a user types in
a String instead of a int the whole program won't go crazy.
And I have no idea how to do that so if you know how please post.
Thanks.
~herocks
Hello everyone,
I trying to make a game in C++ right now and I want to make it so when a user types in
a String instead of a int the whole program won't go crazy.
And I have no idea how to do that so if you know how please post.
Thanks.
~herocks
You could read it into a string, then use a function to extract the number from the string. If there is no number in the string then tell the player they must enter a number. Look up std::stringstream.
Good Luck.
David
Ah, I was thinking of doing that, but I only thought of half of what I should have thought.
Thanks, I'll try it now.
Ok, Now I needa know how to convert a string to a int...I tried using the atoi() function but all it got me was a 0...
You can use stringstream for that.
something like this:
Code:std::string str; int an_int; std::stringstream s; s<< str; s>> an_int;
Thanks, but I just got it to work.
Atoi returned a 0 ( NULL ) because I typed in a letter so I just have to see if the int equals NULL
and if it dose, tell the user that its invalided.
IMO, the easiest way to check if the user inputs a string instead of an int is to check the state of the stream when you read in. When the user inputs a string and you attempt to read in an int, it will go into a fail state. This example clears the fail state, empties the stream of the invalid input, and attempts to read in the int again:You have to #include <limits> and <ios> for numeric_limits and streamsize. You can expand that pretty easily to also "fail" if the user enters an integer followed by characters, like 123abc.Code:int value = 0; while (!(std::cin >> value)) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Error message and prompt again here. }
What about:
vs.Code:cin.ignore(cin.rdbuf()->in_avail() );
Code:cin.ignore(numeric_limits<streamsize>::max(), '\n');
In my experience both work (don't forget the '\n' on the first one), but I believe the standard actually uses the numeric_limits version as an example so I prefer that one. I haven't read enough about in_avail() to be completely confident of its accuracy.
Thanks.