User input(cin) - Default value

前端 未结 4 1672
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 07:57

I can\'t figure out how to use a \"default value\" when asking the user for input. I want the user to be able to just press Enter and get the default value. Consider the fol

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 08:35

    Use std::getline to read a line of text from std::cin. If the line is empty, use your default value. Otherwise, use a std::istringstream to convert the given string to a number. If this conversion fails, the default value will be used.

    Here's a sample program:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        std::cout << "Please give a number [default = 20]: ";
    
        int number = 20;
        std::string input;
        std::getline( std::cin, input );
        if ( !input.empty() ) {
            std::istringstream stream( input );
            stream >> number;
        }
    
        std::cout << number;
    }
    

提交回复
热议问题