【问题标题】:Refer to a std::string as a char*将 std::string 称为 char*
【发布时间】:2021-05-30 12:22:54
【问题描述】:

我想引用(写入)std::string,就像引用字符串文字(char*)一样。这就是我想要做的:

  std::string File::readAll(){
    std::string ret;
    ret.reserve(this->size+1);
    fseek(file, 0, SEEK_SET);

    fread((char*)ret.c_str(), size, 1, this->file);
    ret.append("\0");

    return ret;
  }

当我这样做时,字符串仍然是空的。我怎样才能做到这一点?

【问题讨论】:

  • 这是什么意思?我应该如何更改我的代码?
  • 重新阅读有关保留与调整大小的文档,并考虑哪些字符在哪些时间存在。
  • append 调用没有按照您的想法执行。
  • @1201 这也是不必要的,因为 std::string 总是在末尾隐含一个空字符。

标签: c++ string stdstring


【解决方案1】:

reserve 替换为resize,然后使用.data()(或&ret[0] pre C++17)代替.c_str()

【讨论】:

  • 或者,&ret[0] 在不存在 data() 的早期版本中(C++11 之前),或者仅返回 const char*(C++17 之前)跨度>
  • @RemyLebeau 感谢您的反馈。已添加。
猜你喜欢
  • 2010-11-14
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2011-08-02
  • 2014-07-23
  • 2013-09-10
相关资源
最近更新 更多