'''
int main()
{
struct std::tm tm。
std::istringstream ss("25JUN20")。
ss >> std::get_time(&tm, "%e%b%y"); //在這種情況下只需%T。
std::time_t time = mktime(&tm)。
std::cout << tm.tm_year << std::endl;
}
''
我試著使用這段代碼,但我的年份被歪曲了。 希望能得到任何幫助。
謝謝
uj5u.com熱心網友回復:
即使是對我的問題有一個更簡單的解決方案,也會得到贊賞@S.M.- sparsh jain
使用Howard Hinnant的C 20 chrono預覽庫(開放源代碼,僅有頭檔案),這個問題非常簡單。
#include "date/date.h"
#include <Chrono>
#include <iostream>
#include <sstream>
int
main()
{
std::istringstream ss("25JUN20")。
date::year_month_day ymd;
ss >> date::parse("%d%b%y"/span>, ymd)。
std::cout << date::format("%Y%m%d", ymd) << '
'。
}
輸出:
20200625
format回傳一個std::string,所以你可以用這個結果做任何你需要的事情。
我推薦使用配置宏ONLY_C_LOCALE=1進行編譯。 在gcc和clang上,這是最容易做到的,在命令列中使用-DONLY_C_LOCALE=1。 使用VS,你可以在IDE中設定宏。
我推薦這個宏的原因是,gcc 和 VS std libs 通常不會以不區分大小寫的方式決議月份名稱,而 ONLY_C_LOCALE=1 告訴 date.h 繞過這個錯誤。 如果你使用的是 LLVM 的 libc ,那么這個解決方法就沒有必要了。
這段代碼將被移植到C 20,只需做一些小的改動:
這段代碼將被移植到C 20。
#include <Chrono>
#include <format>
#include <iostream>
#include <sstream>
int
main()
{
std::istringstream ss("25JUN20")。
std::Chrono::year_month_day ymd;
ss >> std::Chrono::parse("%d%b%y"/span>, ymd)。
std::cout << std::format("{:%Y%m%d}", ymd) << '
'。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/311908.html
標籤:
上一篇:如何及時轉換這些欄目
