User input(cin) - Default value

前端 未结 4 1664
没有蜡笔的小新
没有蜡笔的小新 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:24

    I'd be tempted to read the line as a string using getline() and then you've (arguably) more control over the conversion process:

    int number(20);
    string numStr;
    cout << "Please give a number [default = " << number << "]: ";
    getline(cin, numStr);
    number = ( numStr.empty() ) ? number : strtol( numStr.c_str(), NULL, 0);
    cout << number << endl;
    

提交回复
热议问题