c++ - 想要 ostringstream 修改传递的字符串

标签 c++ string visual-studio-2010 c++03 ostringstream

我希望 std::ostringstream 修改我传递给它的字符串:

#include <string>
#include <iostream>
#include <sstream>

void My_Function(std::string& error_message)
{
  std::ostringstream error_stream(error_message);
  // For Nipun Talukdar:
  /* Perform some operations */
  if (/* operation failed */)
  {
      error_stream << "Failure at line: "
                   << __LINE__
                   << ", in source file: "
                   << __FILE__
                   << "\n";
  }
  return;
}

int main(void)
{
  std::string error_message;
  My_Function(error_message);
  std::cout << "Error is: \""
            << error_message
            << "\"\n";
  return 0;
}

使用上面的代码,error_message 的输出为空。

这是因为,according to cppreference.com ,采用 std::streamstd::basic_ostream 的构造函数采用 conststd::字符串。这意味着 std::basic_ostringstream 不会修改传递给它的字符串。引用的引用文献甚至说 std::ostringstream 复制 传递给它的字符串。

为了解决这个问题,我改变了我的功能:

void My_Second_Function(std::string& error_message)
{
  std::ostringstream error_stream;
  error_stream << "Failure at line: "
               << __LINE__
               << "\n";
  error_message = error_stream.str();  // This is not efficient, making a copy!
  return;
}

是否有更有效的方法来对字符串执行格式化输出,例如直接写入(即无需从流中复制)?

我使用的是 Visual Studio 2010,它不支持 C++11。出于开店考虑,升级到2013的理由没有通过。所以我不能使用 C++11 或 C++14 功能。

最佳答案

使用流缓冲区并将放置指针设置为字符串的内部数据:

struct nocopy : std::streambuf
{
    nocopy(std::string& str)
    { this->setp(&str[0], &str[0] + str.size()); }
};

struct nocopy_stream : virtual private nocopy, std::ostream
{
    nocopy_stream(std::string& str)
        : nocopy(str)
        , std::ostream(this)
    { }
};

void My_Function(std::string& error_message)
{
  nocopy_stream error_stream(error_message);
  error_stream << "Failure at line: "
               << __LINE__
               << "\n";
}

int main(void)
{
  std::string error_message;
  error_message.resize(1000);

  My_Function(error_message);
  std::cout << "Error is: \""
            << error_message
            << "\"\n";
}

对于此示例,error_message 必须设置为足够大的大小,因为我们不会重写 overflow() 并且基类版本不执行任何操作。但是,您可以覆盖它以进行正确的大小调整。

关于c++ - 想要 ostringstream 修改传递的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29017133/

相关文章:

Java 使用正则表达式来匹配测验的模式

c# - 在 Visual Studio 2010 中记录 (XML) 应用程序设置

c++ - 将指向模板函数的指针作为函数参数传递?

c++ - 为什么 static void method() const 是编译错误?

Python从列表中删除相同的字符

java - 从Java中的字符串中提取第一个单词的最佳方法是什么?

c - scanf_s 不适用于 Visual Studio C++ 2010 Express 中的 printf

visual-studio-2010 - 提交和更新之间有什么区别?

c++ - 是否可以通过单个指针访问多态类的不同祖先的虚方法?

c++ - 更改 SDL 背景