c++ - 如何从 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?
所以...我该怎么做?
解决方案
有一个非const
data()
自 C++17 以来的版本。
在此之前,你可以通过&str[0]
,这给你同样的东西。
请注意,在 C++11 之前,这在技术上是不安全的,因为 C++98/03 没有明确保证字符串数据的连续存储(尽管出于多种原因,这在实践中通常是这种情况)。
推荐阅读
- javascript - 使用示例数据重新排列 json
- ruby - Ruby 序列化和反序列化结构
- java - 如何使用 Java 获取您在 Chrome 调试器中看到的所有 cookie 信息?
- javafx - JavaFX - FileChooser 因非 AppKit 线程错误而崩溃
- r - 当有多个“键”时如何合并数据集
- function - 使用参数开关更改函数的行为方式
- java - 如何将一组包含对象列表的对象插入 Firebase
- python - 我怎样才能用魔杖作曲?
- ms-access - 您是否能够对整个访问记录使用条件格式?根据一个参数更改整个记录颜色?
- java - React Native:错误:找不到符号 > 新 AppCenterReactNativeAnalyticsPackage(MainApplication.this