Reputation: 65
I'm trying to figure out how to do some date validation. I need to be able to take an input from user in the form of mm/dd/yyyy and do various calculations with it to determine validity. However, I can't figure out how to split the date into three variables day,month,year after I got the input. I've played around with getline and get functions but I can't figure it out. Thanks for any help in advance from a newbie. PS I don't want to use any built in date validation functions.
int main()
{
char fill = '/';
string entered_date;
int entered_month;
int entered_year;
int entered_day;
cout << "Enter a date (mm/dd/yyyy): " << endl;
cin >> entered_date;
//getline(month, 2, '/'); < fix me
//cout << entered_month << "/" << entered_day << "/"
// << entered_year << endl;
system("Pause");
}
Upvotes: 0
Views: 19924
Reputation: 4343
You can use scanf in such a case, as it provides much more functionality than cin.
int mm, dd, yyyy;
scanf("%d/%d/%d", &mm, &dd, &yyyy);
This should hopefully do the trick.
EDIT: Another way to do so would be to take the entire input in the form of a string, and then find substrings and validate each part.
string date;
cin >> date;
string delimiter = "/";
auto start = date.begin(); // iterator at beginning of string
auto finish = date.find(delimiter); // gives position of first occurrence of delimiter
if (finish == date.npos) // find returned the end of string
// delimiter does not exist in string.
else
int month = stoi(date.substr(0, finish)); // Extracts month part from date string
date = date.substr(finish+1); // Removes the month part from the date string
// Understand this piece and write further ahead.
If you know your input will be correct, then use the first part as it will be much faster. If there are chances of incorrect input, use the second as it will be more robust.
Upvotes: 4
Reputation: 35440
The simplest way is to use std::string::substr
, and then call stoi
:
#include <string>
#include <iostream>
using namespace std;
int main()
{
char fill = '/';
string entered_date;
int entered_month;
int entered_year;
int entered_day;
cout << "Enter a date (mm/dd/yyyy): " << endl;
cin >> entered_date;
entered_month = stoi(entered_date.substr(0,2));
entered_day = stoi(entered_date.substr(3,2));
entered_year = stoi(entered_date.substr(6));
}
Live example: http://ideone.com/PWyh8J
Upvotes: 4