how do i stop this error.....
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
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.
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.
Sorry, i dont know how to use this getline method, can you show me the code.
Thanks for the help
Thanks for the help
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:
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!
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!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement