Jump to content

  • Log In with Google      Sign In   
  • Create Account


how do i stop this error.....


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 nws_mrman   Members   -  Reputation: 122

Like
Likes
Like

Posted 25 January 2002 - 06:36 AM

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

Sponsor:

#2 jRaskell   Members   -  Reputation: 220

Like
Likes
Like

Posted 25 January 2002 - 08:07 AM

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.

#3 nws_mrman   Members   -  Reputation: 122

Like
Likes
Like

Posted 27 January 2002 - 12:14 AM

Sorry, i dont know how to use this getline method, can you show me the code.
Thanks for the help

#4 Oluseyi   Staff Emeritus   -  Reputation: 1670

Like
Likes
Like

Posted 27 January 2002 - 06:01 AM

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!





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS