I recently saw the nice answer of Kerrek for a similar problem in SO: Read file line by line with an additional comment for the separator trick.
So, I looked for this and transformed it to your standard input requirement (which was actually easy and less effort):
#include <iostream>
struct Date {
int day, month, year;
};
int main()
{
std::cout<< "Enter employee hired date (dd/mm/yyyy): ";
Date hireDate; char sep1, sep2;
std::cin >> hireDate.day >> sep1 >> hireDate.month >> sep2 >> hireDate.year;
if (std::cin && sep1 == '/' && sep2 == '/') {
std::cout << "Got: "
<< hireDate.day << '/' << hireDate.month << '/' << hireDate.year << '
';
} else {
std::cerr << "ERROR: dd/mm/yyyy expected!
";
}
return 0;
}
Compiled and tested:
Enter employee hired date (dd/mm/yyyy): 28/08/2018
Got: 28/8/2018
Life Demo on ideone
Note:
This doesn't consider a verification of input numbers (whether they form a valid date) nor that the number of input digits match the format. For the latter, it would probably better to follow the hint concerning std::getline()
i.e. get input as std::string
and verify first char
by char
that syntax is correct.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…