User input(cin) - Default value

c++, visual-c++

Solution

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;
}

Problem

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 following piece of code, can you help me? ``` int number; cout << "Please give a number [default = 20]: "; cin >> number; if(???) { // The user hasn't given any input, he/she has just // pressed Enter number = 20; } while(!cin) { // Error handling goes here // ... } cout << "The number is: " << number << endl; ```

Original source