Tuesday, December 16, 2014

Get input from console

If you don't want to trust user input, give this a try:

(Tested with Visual Studio 2012)

template <typename T>
auto GetInput (const std::string &strQuery) -> T
{
    std::cout << strQuery << "\n> " ;

    while (1) {
        T out = T () ;
        std::cin >> out ;

        if (std::cin.good () == false) {
            std::cin.clear () ;
            std::cin.ignore (std::numeric_limits <std::streamsize>::max (), '\n') ;
            std::cout << "Error!" "\n" ;
            std::cout << strQuery << "\n> " ;
            continue ;
        }

        return out ;
    }
}

The line:

auto GetInput (const std::string &strQuery) -> T

can be changed to:

 T GetInput (const std::string &strQuery)

for compilers that do not have C++11 features.

No comments:

Post a Comment