I have the following function that is designed for beginners to make user input easier and leave input stream subtleties until later in their learning path. What do you think?
bool simple_input(T& x);
This function is meant for built-in types and std::strings, although it would work with other types that define operator>>. It reads in the input from cin and places the value into x. If the user input does not match the type, then x is assigned its default value (e.g. 0 or empty string) and false is returned. If the input is successful, the function returns true.
For non-string types, leading or trailing whitespace will cause the function to fail -- the input from the user must match the type. For strings, one entire line is read in, including whitespace.
Regardless of whether the input succeeded or failed, the cin stream will be left in a good state and there will be no more characters in the buffer. Even the trailing newline will be removed.
Here is example usage. It just passes the variable to the function and checks the return value to see if it was successful or not.
And here is my implementation of the function:
cout << "Enter a line of text: ";
cout << "The line of text read in was: " << s << endl;
cout << "Enter an int: ";
cout << "The number read in was: " << i << endl;
cout << "Sorry, invalid int!" << endl;
cout << "Enter a double: ";
cout << "Invalid double! Try again: ";
cout << "The double read in was: " << d << endl;
There are two things I am looking for feedback on:
bool simple_input(T& x)
if (std::cin >> std::noskipws >> x >> std::skipws && std::cin.get() == '\n')
x = T();
bool simple_input<std::string>(std::string& x)
if (std::getline(std::cin, x))
- Usage: Do you think a function like this would make it easier for beginners to learn? How could something like this be packaged so that it could be used by beginners with minimal instruction?
- Implementation: What changes would you make to the implementation? What potential pitfalls do you see arising?
Thanks for your attention.