【发布时间】:2011-05-31 17:20:16
【问题描述】:
我想使用stringstream 提供的工具从固定格式的string 中提取值,作为sscanf 的类型安全替代方案。我该怎么做?
考虑以下特定用例。我有以下固定格式的std::string:
YYYYMMDDHHMMSSmmm
地点:
YYYY = 4 digits representing the year
MM = 2 digits representing the month ('0' padded to 2 characters)
DD = 2 digits representing the day ('0' padded to 2 characters)
HH = 2 digits representing the hour ('0' padded to 2 characters)
MM = 2 digits representing the minute ('0' padded to 2 characters)
SS = 2 digits representing the second ('0' padded to 2 characters)
mmm = 3 digits representing the milliseconds ('0' padded to 3 characters)
以前我是按照这些思路做的:
string s = "20101220110651184";
unsigned year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0;
sscanf(s.c_str(), "%4u%2u%2u%2u%2u%2u%3u", &year, &month, &day, &hour, &minute, &second, &milli );
宽度值是幻数,没关系。为了类型安全,我想使用流来提取这些值并将它们转换为unsigneds。但是当我尝试这个时:
stringstream ss;
ss << "20101220110651184";
ss >> setw(4) >> year;
year 保留值0。应该是2010。
我该如何做我想做的事?我不能使用 Boost 或任何其他 3rd 方库,也不能使用 C++0x。
【问题讨论】:
-
*Bill 等不及要他的“Standard C++ IOstreams and Locales”副本了...+1
-
setw()用于写入输出。它不适用于阅读。 -
也许你应该在提取第一个字段之前回到流的开头。
-
@Ben:或者更好,只是
std::stringstream ss("20101220110651184"); -
@Karl:无关紧要,但只要说它不是我们树的一部分就够了。
标签: c++