Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c++ - input day,month,year and store in a seperate structure

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...