如何修改此代码以便能够正确解析此字符串" 22/12/2016 01:12:10 "到 date_time 变量?
struct tm date_time = {};
std::wstring dateTimeFormat{ L"%d/%m/%Y %H:%M:%S" };
std::istringstream ss("22/12/2016 01:12:10");
ss >> std::get_time(&date_time, dateTimeFormat.c_str());
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools
\msvc\14.12.25827\include\iomanip(190): error C2338: wrong character type for
get_time
1>c:\...\procedure.cpp(70): note: see reference to function template
instantiation 'std::basic_istream<char,std::char_traits<char>> &std::operator
>><char,std::char_traits<char>,_Elem>(std::basic_istream<char,std::char_traits<char>>
&,const std::_Timeobj<_Elem,tm *> &)' being compiled
1> with
1> [
1> _Elem=wchar_t
1> ]
1>Done building project "projectname" -- FAILED.
答案 0 :(得分:1)
您正在将宽字符与窄字符混合。
对于宽字符,代码应为:
struct tm date_time = {};
std::wstring dateTimeFormat{L"%d/%m/%Y %H:%M:%S"};
std::wistringstream ss(L"22/12/2016 01:12:10");
ss >> std::get_time( &date_time, dateTimeFormat.c_str() );
对于狭窄的字符,它应该是:
struct tm date_time = {};
std::string dateTimeFormat{"%d/%m/%Y %H:%M:%S"};
std::istringstream ss("22/12/2016 01:12:10");
ss >> std::get_time( &date_time, dateTimeFormat.c_str() );
无论哪种方式都需要以下标题:
#include <iomanip>
#include <sstream>