C++ to check if user input is a number, not a character or a symbol

后端 未结 2 881

I have been trying to incorporate a check to see if the input from the user is a valid input. For example my program wants the user to guess a number between 1-1000. My prog

2条回答
  •  一个人的身影
    2020-12-10 10:05

    Since spreading around code similar to what @nhgrif suggests for every acquisition is tedious and error-prone, I usually keep around the following header:

    #ifndef ACQUIREINPUT_HPP_INCLUDED
    #define ACQUIREINPUT_HPP_INCLUDED
    
    #include 
    #include 
    #include 
    
    template void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result)
    {
        do
        {
            Os<::max(), '\n');
            }
            Is>>Result;
            if(Is.fail())
                Os< InType AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString)
    {
        InType temp;
        AcquireInput(Os,Is,Prompt,FailString,temp);
        return temp;
    }
    
    #endif
    

    Usage example:

    //1st overload
    int AnInteger;
    AcquireInput(cout,cin,"Please insert an integer: ","Invalid value.\n",AnInteger);
    
    //2nd overload (more convenient, in this case)
    int AnInteger=AcquireInput(cout,cin, "Please insert an integer: ","Invalid value.\n");
    

    The AcquireInput function allows to read any type for which there's an operator>> available and automatically retries (cleaning up the input buffer) if the user inserts invalid data. It also prints the given prompt before asking the data and the error message in case of invalid data.

提交回复
热议问题