Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Currently i am working on a task that need me to store the date in to structure(day,month,year) but i dont know how to seperate it when user enter all in one line

struct Date
{

int day;
int month;
int year;
}hire_date;

int main()
{

cout<<"Enter employee hired date(dd/mm/yyyy) :";

cin>>hire_date.day;
cin>>hire_date.month;
cin>>hire_date.year;`
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...