首页 > 解决方案 > 如何从 istream 中使用特定数量的字节创建字符串?

问题描述

我需要使用 istream 的前 N ​​个字节创建一个 std::string ......我该怎么做?

std::istream istm;

std::string  str;
istm >> str;              //will read tons of stuff until finds whitespace

std::string  str(N, ' ');
istm.read(str.data(), N); //can't write into buffer inside string, cause data() returns const char*

std::unique_ptr<char[N+1]> buf;
istm.read(buf.get(), N);
std::string str(buf.get());                //should work, but why extra buffer?

所以...我该怎么做?

标签: c++stringistream

解决方案


有一个非const data()自 C++17 以来的版本。

在此之前,你可以通过&str[0],这给你同样的东西。

请注意,在 C++11 之前,这在技术上是不安全的,因为 C++98/03 没有明确保证字符串数据的连续存储(尽管出于多种原因,这在实践中通常是这种情况)。


推荐阅读