How to TRULY validate basic string input?

Is it even possible using cin to "truly" validate input (i.e., prevent user from crashing the program by mashing the keyboard)? Despite my best efforts, this code hangs quite easily with a little keyboard mashing. Any thoughts? Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

valFlag = 0;
int rep;
char ans[6];

while(!valFlag) //Repeat until input is valid
        { 
                cout << "\nEnter Hit, Stand, or Quit: ";

                cin.get(ans, 6, '\n');
                cin.ignore(100, '\n');

                int len = strlen(ans);

                for (int i = 0; i < len; ++i)   //Set answer to lowercase
                {
                        if(isupper(ans[i]))
                                ans[i] = tolower(ans[i]);
                }

                if (!strcmp (ans, "hit") ||  \
                    !strcmp (ans, "stand") || \
                    !strcmp (ans, "quit"))
                {
                        valFlag = 1;
                }
                else
                {
                        cout << "\nInvalid input. Enter Hit, Stand, or Quit: ";
                }
Firstly :
char ans[6];

You should have increased the array size to the point even a naughty user can hardly make your program crazy. With the current size of 6, an input string with length of 7 or more can possibly cause buffer overflow, and even segfaults.

So :
1
2
char ans[10000];
cin.get(ans, sizeof(ans), '\n');
SOLVED? used cin >> ans instead of cin.get... because cin.get was causing segmentation error? Not sure why. We'll leave it up to the experts...
Better yet, use std::string instead. They offer better memory management than you think, and you don't need to spend lots of extra memory just for the sake of repelling possible stupid pranks from a naughty user.

1
2
std::string ans;
getline(cin, ans, '\n'); 
> I use cin >> ans instead of cin.get... Because cin.get was causing segmentation error?

But you still can't escape the problem. The cin >> ans seperates inputs with whitespaces, but it can still cause buffer overflow or segfaults if an user enters a very long string without a space and the size of your char-array is too small. If a naughty user enters a brief string and a space and hold a key for very long then finally press Enter, your program will possibly go bankrupt and end up being even more crazy. You can somehow counter it by calling cin.ignore() with the highest possible value if you can though, but not recommended.
Last edited on
That still sounds kind of silly. Cin >> get should be sufficient for 1st year CS student program. ;)
> Cin >> get should be sufficient for 1st year CS student program
Of course! If you don't try to be crazy, then it's more than sufficient :)
Topic archived. No new replies allowed.