C++ 如何从C+中的字符串ID中提取int day、month和year+;

C++ 如何从C+中的字符串ID中提取int day、month和year+;,c++,class,C++,Class,我在大学开始做这个程序,但我还有一些在家里做的功能:getbirth和age。如何从字符串ID中获取日、月、年作为整数 我试着只使用字符串,但它不起作用 #include <iostream> #include <string> using namespace std; enum Sex {male,female,unknown}; //const class Person //class { private: string name; strin

我在大学开始做这个程序,但我还有一些在家里做的功能:
getbirth
age
。如何从字符串ID中获取日、月、年作为整数

我试着只使用字符串,但它不起作用

#include <iostream>
#include <string>
using namespace std;

enum Sex {male,female,unknown};  //const
class Person   //class
{
private:
    string name;
    string ID;   //this is the problem
    Sex pol;
....
void getBirthday(int &day,int&month,int&year)  //even if i use string for day...it is not working
{}
...
int main()
{Person p1("ALEX","9510167954")...;}   //95-year,10-month,16-day*this is what my teacher wrote
#包括
#包括
使用名称空间std;
枚举性别{男性,女性,未知}//常数
班级人员//班级
{
私人:
字符串名;
string ID;//这就是问题所在
性政策;
....
void getbirth(int&day、int&month、int&year)//即使我使用字符串表示日期,它也不起作用
{}
...
int main()
这是我的老师写的

我期望输出:16/10/95

尝试初始化
getbirth()
参数,如下所示:

day = stoi(ID.substr(0,2));
month = stoi(ID.substr(2, 2));
year = stoi(ID.substr(4, 2));

请看一看标准流操纵器。您可以使用将
ID
字符串解析为流

#include <sstream>
#include <iomanip>
#include <ctime>

void getBirthday(int &day, int &month, int &year)
{
    std::istringstream iss(ID);
    std::tm t = {};
    iss >> std::get_time(&t, "%y%m%d");
    if (iss.fail()) {
        // do something, like throw an exception ...
    }
    day = t.tm_mday;
    month = 1 + t.tm_mon;
    year = 1900 + t.tm_year;
}
#包括
#包括
#包括
void getbirth(整数和天、整数和月、整数和年)
{
std::istringstream iss(ID);
std::tm t={};
iss>>标准::获取时间(&t),%y%m%d);
if(iss.fail()){
//做一些事情,比如抛出异常。。。
}
日=t.tm\u mday;
月份=1+t.tm\u月;
年份=1900+t.tm_年;
}
你说的“不工作”是什么意思?当你发布它时,你的代码甚至没有编译。。。