我无法找到以下行为的解释:
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
#include <sstream>
TEST_CASE(rdbuf) {
{
boost::iostreams::stream<boost::iostreams::file_sink> file("test");
file << "Hello, World!";
}
{
boost::iostreams::stream<boost::iostreams::file_source> file("test");
std::string line;
std::getline(file, line);
CHECK_EQUAL(line, "Hello, World!");
}
{
boost::iostreams::stream<boost::iostreams::file_source> file("test");
std::istringstream iss;
std::string line;
file.rdbuf(iss.rdbuf());
std::getline(file, line);
CHECK_EQUAL(line, "");
std::getline(iss, line);
CHECK_EQUAL(line, ""); // (1) Why?
}
{
boost::iostreams::stream<boost::iostreams::file_source> file("test");
std::ostringstream oss;
std::string line;
file.rdbuf(oss.rdbuf());
std::getline(file, line);
CHECK_EQUAL(line, "");
line = oss.str();
CHECK_EQUAL(line, ""); // (2) Why?
}
}
在(1)
和(2)
这两个实例中,我更期待
CHECK_EQUAL(line, "Hello, World!");
成功。
我在这里真正想念的是什么?感谢。
答案 0 :(得分:0)
你这样做是错误的。您要将streambuf
从istringstream
分配到filestream
,您应该从另一个方向进行分配。即:
boost::iostreams::stream<boost::iostreams::file_source> file("test");
std::istringstream iss;
std::string line;
iss.rdbuf(file.rdbuf()); //assign the file to iss
std::getline(file, line);
CHECK_EQUAL(line, "Hello, World!");
std::getline(iss, line);
CHECK_EQUAL(line, ""); // Empty, because the streambuf is shared.