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;
tumchaaditya
  • 1,219
  • 6
  • 19
  • 46

4 Answers4

14

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;
}
Frerich Raabe
  • 86,449
  • 18
  • 111
  • 204
  • 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. – tumchaaditya Apr 26 '12 at 02:44
12

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.

chris
  • 58,138
  • 13
  • 137
  • 194
0
if(!cin)
   cout << "No number was given.";
else
   cout << "Number " << cin << " was given.";
Reteras Remus
  • 899
  • 5
  • 19
  • 34
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;
Component 10
  • 9,937
  • 5
  • 44
  • 62