Home > Software engineering >  how do I store month, day and year in 3 separate variables from the same input? (C ). it needs to b
how do I store month, day and year in 3 separate variables from the same input? (C ). it needs to b

Time:09-30

int month, day, year;
cout << "Enter your date of birth" << endl;
cout << "format: month / day / year  -->" << endl;
cin >> month;
cin >> day;
cin >> year;

it needs to be in MM / DD / YYYY with spaces between the /.

CodePudding user response:

As per this answer on a similar question, you can't cin multiple variables in a single shot, but you should be able to chain multiple cin, type in a single input and have each cin get its own value from standard input.

NOT TESTED

int year, month, day;
char slash;

// example input: 2022 / 10 / 12
cin >> year >> slash >> month >> slash >> day;

CodePudding user response:

You can use strptime to parse time from input. For example.

struct tm t {0};
std::string input;
std::cin >> input;
if (strptime(input.c_str(), "%m/%d/%Y", &t)){
    int d = t.tm_mday;
    int m = t.tm_mon   1;
    int y = t.tm_year   1900;
} else {
    std::cout << "invalid date format\n";
}
  • Related