如何从C++中的字符串ID中提取int日,月和年

How to extract int day, month and year from string ID in C++

本文关键字:int 提取 ID C++ 字符串      更新时间:2023-10-16

我在大学开始做这个程序,但我还有一些功能可以在家里做:getBirthdayage。如何从字符串 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

我期望输出:16/10/95

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

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

看看标准的std::get_time流操纵器。可以使用std::istringstreamID字符串分析为流。

#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;
}