If user enters date in mm / dd / yyyy
format, how do I retrieve it correctly?
std::cin >> month >> day >> year;
does not work.
CodePudding user response:
Have a look at std::get_time()
, eg:
#include <iomanip>
#include <ctime>
std::tm tmb;
std::cin >> std::get_time(&tmb, "%m/%d/%Y");
int month = tmb.tm_mon 1;
int day = tmb.tm_mday;
int year = tmb.tm_year 1900;
CodePudding user response:
First of all, you can define these variables to save the values:
int month;
int day;
int year;
char dummy;
Then you have two options:
- Capture all the values assuming the data will be typed in this format month/day/year, the "/" will be saved in the variable called dummy and the information for the date on the ints:
cin >> month >> dummy >> day >> dummy >> year;
- Or you can capture the data using the same format month/day/year, and validate that each int is separated by a "/" (for this case is not required to define a char variable):
cin >> month;
if (cin.get() != '/')
{
cout << "Follow the format month/day/year" << endl;
return 1;
}
cin >> day;
if (cin.get() != '/')
{
cout << "Follow the format month/day/year" << endl;
return 1;
}
cin >> year;