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
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.
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.
> 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.