User input(cin) - Default value

前端 未结 4 1663
没有蜡笔的小新
没有蜡笔的小新 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;
    
    0 讨论(0)
  • 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 <iostream>
    #include <sstream>
    #include <string>
    
    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;
    }
    
    0 讨论(0)
  • 2020-12-10 08:36

    This works as an alternative to the accepted answer. I would say std::getline is a bit on the overkill side.

    #include <iostream>
    
    int main() {
        int number = 0;
    
        if (std::cin.peek() == '\n') { //check if next character is newline
            number = 20; //and assign the default
        } else if (!(std::cin >> number)) { //be sure to handle invalid input
            std::cout << "Invalid input.\n";
            //error handling
        }
    
        std::cout << "Number: " << number << '\n';    
    }
    

    Here's a live sample with three different runs and inputs.

    0 讨论(0)
  • 2020-12-10 08:36
    if(!cin)
       cout << "No number was given.";
    else
       cout << "Number " << cin << " was given.";
    
    0 讨论(0)
提交回复
热议问题