【问题标题】:How can I create string out of specific amount of bytes from istream?如何从 istream 中使用特定数量的字节创建字符串?
【发布时间】:2020-11-24 14:29:02
【问题描述】:

我需要用 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?

那么...我该怎么做才好呢?

【问题讨论】:

  • 为什么不一次只读取一个字节,也许使用for 循环?

标签: c++ string istream


【解决方案1】:

自 C++17 以来有一个非const data()

在此之前,您可以改为传递&amp;str[0],这给了您同样的东西。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 2014-01-04
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多