我认为这是一个非常简单的问题。我特别想使用 std::get_time ,但它需要某种类型的流来使用。我正在 string_view
中传递数据,并且希望避免仅仅为了解析日期而复制它。
最佳答案
您可以使用 Boost.Iostreams 库轻松做到这一点:
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
#include <string>
int main() {
std::string_view buf{"hello\n"};
boost::iostreams::stream<boost::iostreams::basic_array_source<char>> stream(buf.begin(), buf.size());
std::string s;
stream >> s;
std::cout << s << '\n';
}
<小时/>
您应该可以使用 std::stringstream
来做到这一点和 std::basic_stringbuf<CharT,Traits,Allocator>::setbuf
但 C++ 标准未能满足其要求:
The effect [of
setbuf
] is implementation-defined: some implementations do nothing, while some implementations clear thestd::string
member currently used as the buffer and begin using the user-supplied character array of sizen
, whose first element is pointed to bys
, as the buffer and the input/output character sequence.
关于c++ - 有没有办法从 string_view 创建字符串流而不复制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524805/