• Advertisement

Archived

This topic is now archived and is closed to further replies.

how do i stop this error.....

This topic is 5836 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have just programmed a very basic game of noughts and crosses using ''cin'' to recieve input from the user. They have to enter a number between 1 and 9 for their position. I have programmed it so that if the number is not between 1 and 9 the user is asked to enter the number again, but if a letter is entered it goes mental, or if a number with more than 4 digits is entered it does the "illegal operation" thing. How can i stop these errors occuring? Thanks

Share this post


Link to post
Share on other sites
Advertisement
One way would be to use the getline method of cin.

You can specify the maximum number of characters to allow with getline. You could set the max number to 1 character then you can convert that to an int from there. Maybe check that it isn''t an alpha character, and as long as it''s a number 1-9 you can convert to int using atoi(ascii to int). There may be other ways, but that''s the way I use cin when I need to parse the input for something specific. I don''t know if there''s a cin method that you can specify formatting to or not.

Share this post


Link to post
Share on other sites
You don''t really need getline; as long as the user doesn''t input a space, doing cin >> inp; should work just fine. Make sure your input variable is declared as an integer (int/short/long) and not as char.

Anyway, here''s how to use getline. It''s in the new C++ Standard Library, so you''ll need to use the new-style standard headers as well as the std namespace:

#include <iostream>
using namespace std;
//
...
getline(cin, inp); // default, gets everything up to newline
...
getline(cin, inp, 4); // gets up to 4 characters

You might also want to look into the string class, as it makes text manipulation much easier.


[ GDNet Start Here | GDNet FAQ | MS RTFM | STL | Google ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites

  • Advertisement