简体   繁体   English

输入日、月、年并存储在单独的结构中

[英]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;`
}

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 中看到了 Kerrek 对类似问题的很好的回答:逐行读取文件,并附上分隔符技巧的附加注释。

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 << '\n';
  } else {
    std::cerr << "ERROR: dd/mm/yyyy expected!\n";
  }
  return 0;
}

Compiled and tested:编译和测试:

Enter employee hired date (dd/mm/yyyy): 28/08/2018
Got: 28/8/2018

Life Demo on ideone 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() ie get input as std::string and verify first char by char that syntax is correct.对于后者,它可能会更好地遵循提示有关std::getline()即得到输入作为std::string ,并确认第一charchar是语法是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM