/* Here is some sample user input code I found on the web. It seems to handle user input very well. How do I get user input from cin using >> into X type? Using the >> operator opens you up to alot of problems. Just try entering some invalid data and see how it handles it. cin is notorious at causing input issues because it doesn't remove the newline character from the stream or do type-checking. So anyone using cin >> var; and following it up with another cin >> stringtype; or getline(); will receive empty inputs. It's best practice to NOT MIX the different types of input methods from cin. I know it's going to be easier to use cin >> integer; than the code below. However, the code below is type-safe and if you enter something that isn't an integer it will handle it. The simple code above will simply go into an infinite loop and cause undefined behaviour in your application. Another dis-advantage of using cin >> stringvar; is that cin will do no checks for length, and it will break on a space. So you enter something that is more than 1 word, only the first word is going to be loaded. Leaving the space, and following word still in the input stream. A more elegant solution, and much easier to use is the getline(); function. The example below shows you how to load information, and convert it between types. */ #include #include #include using namespace std; int main() { string input = ""; // How to get a string/sentence with spaces cout << "Please enter a valid sentence (with spaces):\n>"; getline(cin, input); cout << "You entered: " << input << endl << endl; // How to get a number. int myNumber = 0; while (true) { cout << "Please enter a valid number: "; getline(cin, input); // This code converts from string to number safely. stringstream myStream(input); if (myStream >> myNumber) break; cout << "Invalid number, please try again" << endl; } cout << "You entered: " << myNumber << endl << endl; // How to get a single char. char myChar = {0}; while (true) { cout << "Please enter 1 char: "; getline(cin, input); if (input.length() == 1) { myChar = input[0]; break; } cout << "Invalid character, please try again" << endl; } cout << "You entered: " << myChar << endl << endl; cout << "All done. And without using the >> operator" << endl; return 0; }