AgentBanana
AgentBanana

Reputation: 11

How to read a date with cin

If user enters date in mm / dd / yyyy format, how do I retrieve it correctly?

std::cin >> month >> day >> year; does not work.

Upvotes: 1

Views: 623

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596156

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;

Upvotes: 2

Felipe Castro
Felipe Castro

Reputation: 73

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:

  1. 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;
  1. 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;

Upvotes: 0

Related Questions