I am writing this function to ask for a particular input type. is_type just validates that the string recieved can be casted using stringstream to the desired type.
template<typename T>
T get_type(std::string prompt)
{
T output;
std::cout << prompt;
std::string Input;
while (std::getline(std::cin, Input) && !is_type<T>(Input))
{
std::cout << "Invalid input type. Please try again:\n"
<< prompt;
}
std::stringstream(Input) >> output;
return output;
}
The functions seems to work as desired except when I type ctrl + Z for example. What is the appropriate way to deal with this?
I added:
template<typename T>
T get_type(std::string prompt)
{
T output;
std::cout << prompt;
std::string Input;
while (std::getline(std::cin, Input) && !is_type<T>(Input))
{
std::cout << "Invalid input type. Please try again:\n"
<< prompt;
}
if (!std::cin)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
output = get_type<std::string>(prompt) ;
return output;
}
std::stringstream(Input) >> output;
return output;
}
Which asks again for input after for example ctrl+Z Does that solve my problem of std::getline(std::cin, std::string) failing under kewyboard input from the user?
Also, why do I have to hit enter 2 times for the
output = get_type<std::string>(prompt) ;
line to run inside the if.
is_type
seems redundant, since you can simply check the result ofstringstream::operator>>
inside the loop, instead of after the loop ends – Remy Lebeau