【发布时间】:2015-03-12 18:04:26
【问题描述】:
我想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::stream 的 std::basic_ostream 的构造函数采用 const 对 std::string 的引用。这意味着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 的特性。
【问题讨论】:
-
使用流缓冲区并相应地设置放置指针。
-
与问题无关,但它不会总是打印相同的行号吗?
-
@NipunTalukdar:
__LINE__宏返回源代码中的行号。如果在__LINE__宏的位置之前插入或删除代码,行号可能会改变。 -
@0x499602D2:请提供包含您评论示例的答案。谢谢。
-
@ThomasMatthews 是的。但它总是会在 My_Function 中打印相同的行号。因此,每次调用 My_Function 都会输出相同的行号。
标签: c++ string visual-studio-2010 c++03 ostringstream