Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User input(cin) - Default value

Tags:

c++

visual-c++

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;
like image 740
tumchaaditya Avatar asked Apr 25 '12 11:04

tumchaaditya


People also ask

What is input Cin?

cin is a predefined variable that reads data from the keyboard with the extraction operator ( >> ). In the following example, the user can input a number, which is stored in the variable x .

How do you take CIN input?

It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source. For reading inputs, the extraction operator(>>) is combined with the object cin. The data is extracted from the object cin, which is entered using the keyboard by the extraction operator.

What data type is Cin?

cin is an object of istream class type.

How do you input a number in C++?

In the above program, the user enters the number using the cin object. cout<<"Enter the number: "; cin>>num; Then the number is displayed using the cout object.


1 Answers

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;
}
like image 132
Frerich Raabe Avatar answered Oct 22 '22 00:10

Frerich Raabe