gpt4 book ai didi

c++ - std::time_get - 来自 std::cin 的输入正常;来自 std::istringstream 的输入给出错误

转载 作者:行者123 更新时间:2023-11-30 05:05:18 25 4
gpt4 key购买 nike

我已使用 std::time_get::get_date() 方法从以下来源读取日期:

  1. std::cin

  2. 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读取时会出现这个错误?

最佳答案

您认为 eof 意味着发生了错误。

替换这个:

if (err)

if (err & (ios::failbit | ios::badbit))

关于c++ - std::time_get - 来自 std::cin 的输入正常;来自 std::istringstream 的输入给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48464982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com