6

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;

4 Answers 4

15

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

is there any way to check if user is entering a valid input(as there is in cin). I mean, I want to detect when user enters some characters instead of just numbers and throw an error message.
13

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.

1 Comment

For what it's worth, I concur - I like your version better than mine.
0
if(!cin)
   cout << "No number was given.";
else
   cout << "Number " << cin << " was given.";

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.