我使用std::time_get::get_date()
方法从以下来源读取日期:
std::cin
std::istringstream
基于string s
,其值已从std::getline(std::cin, s)
获得。
来自std::cin
的输入正常;日期读得正确,打印得很好。
但是,来自std::istringstream
的输入会出错;日期未正确阅读。
以下是std::istringstream
来源的代码:
http://coliru.stacked-crooked.com/a/31704818a11d5629
vector<string> locales {"C"};
/// Get I/P from a string.
void IPFromStr()
{
cout << "\nI/P from a string ... " << endl;
/// For each locale name
for (const auto& locs : locales)
{
cout << "locale name: " << locs << endl;
try
{
/// Create the locale.
locale loc {locs};
/// Read date/time parts from a string.
ReadDtPartFromStr(loc);
}
catch (const exception& e)
{
cerr << " Exception: " << e.what()
<< endl << endl;
}
}
}
/// Read date/time parts from a string.
void ReadDtPartFromStr(locale& loc)
{
/// Get the time_get<> facet.
const time_get<char>& tg =
use_facet<time_get<char>> (loc);
/// I/P string variable for the read date part.
string dtpart {};
/// output arguments for the time_get<> facet
struct tm d {}; /// time
ios_base::iostate err = ios_base::goodbit; /// good
getline(cin, dtpart);
cout << " dtpart: " << dtpart << endl;
/// Get an istringstream for the read date part
istringstream isdtpart {dtpart};
isdtpart.imbue(loc);
istreambuf_iterator<char> frm(isdtpart), end;
/// Read the date part.
tg.get_date(frm, end,
isdtpart,
err,
&d);
/// Print the date read.
Print(err, d);
}
Print()
功能是:
/// Print the date read.
void Print(ios_base::iostate& err, tm& d)
{
if (err)
cout << " error while reading input" << endl;
else
cout << " yyyy/mm/dd hh:mm:ss : "
<< d.tm_year + 1900 << '/'
<< d.tm_mon + 1 << '/'
<< d.tm_mday << ' '
<< d.tm_hour << ':'
<< d.tm_min << ':'
<< d.tm_sec
<< endl;
}
给出以下std::cin
输入:
01/26/2018
我得到以下输出:
I/P from a string ...
locale name: C
dtpart: 01/26/2018
error while reading input
相同的输入适用于直接从std::cin
读取的类似函数。
为什么我从std::istringstream
?
答案 0 :(得分:1)
你正在接受eof意味着发生错误。
替换它:
if (err)
与
if (err & (ios::failbit | ios::badbit))