如何从C++中的字符串ID中提取int日,月和年
How to extract int day, month and year from string ID in C++
我在大学开始做这个程序,但我还有一些功能可以在家里做:getBirthday
和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
我期望输出: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::istringstream
将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;
}
相关文章:
- 从 std::vector<无符号字符>切片中提取 int?
- z3 提取 Seq Int 作为 std::vector<int>
- 如何安全地将有符号字段从uint32_t提取到有符号数字(int或uint32_t)中
- 如何从C++中的字符串ID中提取int日,月和年
- 从 vector<pair<string, int 中提取不包含 0 的字符串>>
- 从字符串中提取单个字符并将其转换为 int
- 从字符串中提取int值和字符串
- 正则表达式:在字符串和冒号之后提取 int
- 如何在不使用堆栈或数组的情况下从INT中提取每个数字?(C )
- 从长长的长度中提取int
- c++使用字符串流从字符串内部提取int
- 从文本文件中提取特定值(char & int)并插入到多个变量中C++
- 字符串解析以在C++中为Arduino提取int
- 在C++中使用sscanf从字符串中提取int
- 正在C++中提取char数组的int
- 从包含特殊字符的char*中提取int
- c++文件提取检查是否为int
- 使用文件提取操作符读取int或string
- 为什么当我提取到"char"和"int"时,IOStream的EOF标志行为会有所不同?
- 从 std::map<int, std::vector 中提取向量>