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;
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 .
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.
cin is an object of istream class type.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With