Rez*_*aee 7 c++ g++ clang istream clang++
这是一个示例代码:
#include <iostream>
#include <stdexcept>
#include <cstring>
#include <ctime>
#include <sstream>
using std::cout;
using std::endl;
std::size_t const BUF_SIZE(1000);
std::ostream& operator<<(std::ostream& os, std::tm const& rhs)
{
os << asctime(&rhs);
return os;
}
std::istream& operator>>(std::istream& is, std::tm& rhs)
{
while (is.peek() == ' ' || is.peek() == '\t')
{
is.get();
}
std::streampos curPos = is.tellg();
char buf[BUF_SIZE];
is.getline(buf, BUF_SIZE);
char* ptr = strptime(buf, "%D %T", &rhs);
if (ptr == 0)
{
throw std::runtime_error("strptime() failed!");
}
std::size_t processed = ptr - buf;
is.seekg(curPos + static_cast<std::streampos>(processed));
return is;
}
int main()
{
std::istringstream is("10101 07/09/12 07:30:00 123.24");
int uuid(0);
double price(0);
std::tm ptime; std::memset(&ptime, 0, sizeof(tm));
is >> uuid >> ptime >> price;
cout << "UUID: " << uuid << endl;
cout << "Time: " << ptime;
cout << "Price: " << price << endl;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试重载struct tm的<<和>>运算符!如果我使用g ++编译我的代码并运行它,我得到:
UUID: 10101
Time: Sun Jul 9 07:30:00 2012
Price: 123.24
Run Code Online (Sandbox Code Playgroud)
完善!
但是,如果我使用clang ++编译它,我得到:
UUID: 10101
Time: Sun Jul 9 07:30:00 2012
Price: 0
Run Code Online (Sandbox Code Playgroud)
OOPS!
到底是怎么回事?这是clang的一个问题,还是我处理istream的方式?
我能够重现这个(g ++ 4.7.0和clang ++ 3.1与libc ++ - svn),并且一个简短的调试会话显示clang ++设置了eofbitafter getline(这是正常的),然后以某种方式导致seekg设置failbit.这听起来像一个bug,鉴于seekg first clears eofbit(§27.7.2.3/ 41)
要解决,请插入和is.clear()之间的任何位置.getlineseekg