c++ - cout 一个返回的字符串

标签 c++ string cout

所以我有一个名为 array 的类(class)我想将其作为格式化字符串返回,如下所示:[first, second, third, ..., last] .现在我写了试图这样做的方法:

std::string& array::to_string()
{
    char buffer[1];
    std::string s("[");
    for (auto &x: *this)
    {
        if (&x == this->end()) s += _itoa_s(x, buffer, 10) + "]";
        else s += _itoa_s(x, buffer, 10) + ",";
    }
    return s;
}

是的,我已经包含了 <string> .现在,在我程序的另一部分,我使用 std::cout << myArray.to_string() << '\n' .我得到的错误(在执行期间)只是 Visual Studio 把我扔到 stdlib.h标题并显示它的这一部分:

__DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_1(
    _Success_(return == 0)
    errno_t, _itoa_s,
    _In_ int,  _Value,
         char, _Buffer,
    _In_ int,  _Radix
    )

我做错了什么?

最佳答案

字符串 s 是函数 to_string 的本地字符串,它的析构函数作为 to_string 返回运行,因此返回并使用对已经销毁的字符串会产生未定义的行为。改为按值返回它:

std::string array::to_string() const
{
    // a more robust, C++-style implementation...
    std::ostringstream oss;
    size_t n = 0;
    for (const auto& x: *this)
        oss << (n++ ? ',' : '[') << x;
    oss << ']';
    return oss.str();
}

关于c++ - cout 一个返回的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42583630/

相关文章:

c++ - 如何在cpp和c中不使用cout/printf输出文本?

python3 字符串 "abcd"打印 : aababcabcd?

java - 删除方括号并替换为大括号

c++ - 将唯一指针引用保存到唯一指针引用

c++ - 如何在 C++ 中滚动锁定报表样式 ListView 的第一列

python - 基于 Python 中的字典/列表标记单词

C++ streamsize prec = cout.precision(3) - 它是如何工作的?

C++11 为什么 cout 从 bool 数组打印大整数?

c++ - 如何使用 shared_ptr 确保指针存在?

c++ - 使用 Opencv 如何在消除框内打印的对象的同时检测图像中的框?