有没有办法在我读取boost归档文件后检测其中是否还有剩余内容?我尝试了这段代码:
const string s1("some text");
std::stringstream stream;
boost::archive::polymorphic_text_oarchive oAr(stream);
oAr << s1;
boost::archive::polymorphic_text_iarchive iAr(stream);
string s2;
iAr >> s2;
if (!stream.eof())
{
// There is still something inside the archive
}我期望更新流对象就像我直接从它读取一样,但在上面的代码中,stream.eof()始终是false,尽管我读取了我编写的所有内容。将string更改为int会得到相同的结果。
我想要这种能力的原因是,当我读到的类型与我写的类型不同时:
const string s1("some text");
std::stringstream stream;
boost::archive::polymorphic_text_oarchive oAr(stream);
oAr << s1;
boost::archive::polymorphic_text_iarchive iAr(stream);
int s2;
iAr >> s2; // string was written but int is read我知道在这种情况下我无能为力,但我希望至少检查我是否读取了所有内容,这将给我一些指示,表明读取和写入之间是否存在某些不一致。有什么想法吗?
发布于 2010-08-30 16:24:05
可以在文件结束后尝试读取某些内容时设置stream.eof(),而不是在从文件中读取最后一个字节时设置。
在流中启用异常并尝试读取直到抛出异常可能会起作用。
发布于 2010-08-30 17:24:39
在尝试某些操作之前,流不能设置任何标志。
可以使用peek()查看并返回流中的下一个字符,但不能将其删除。这足以设置一个标志,所以可以这样做:if (stream.peek(), !stream.eof()) /* peek was not eof */。
https://stackoverflow.com/questions/3598775
复制相似问题