You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++自定义Vector向任意输出流传输数据时输出乱码如何解决

手写Vector数据结构的输出乱码问题与修复

我没有使用现成模板,从零开始手写实现数据结构,目前已经完成了Vector的简易原型。

这个数据结构包含名为print的成员方法,为了支持传入任意类型的输出流,我给该方法添加了std::ostream&类型参数:既可以传入全局std::cout将内容输出到控制台,也可以传入stringstream等其他输出流,方便后续开展单元测试。

所有代码写完后可以正常编译,但使用std::cout流输出时控制台出现异常乱码,典型输出结果为, ⌂≈⌂┘≈⌂.┘≈⌂┴.┘≈⌂☺70。我最初怀疑是print方法循环越界读取了内存垃圾数据,但调试后没有发现逻辑异常。

初始实现代码

首先是print方法的初始实现:

void Vector::print(std::ostream& stream)
{
    auto index = 0;

    while (index < this -> size) {
        auto value = this->get(index);

        if (index < (this->size - 1))
            stream << value + ", ";
        else
            stream << value;

        index++;
    }
}

main.cpp中的测试代码如下:

using std::cout; 
using std::cin; 
using std::endl;
using std::getline; 


int main(int argc, char* argv[])
{

    Vector numbers(11);

    auto index = 0;
    unsigned long v_size = numbers.getSize(); 

    while (index < v_size) {
        numbers.set(index, (index * 7));
        index++;
    }

    numbers.print();

    return 0;
}

修复更新

参考其他开发者提供的问题排查思路,我已经完成了问题修复,新的实现如下。

更新后的print方法代码:

void Vector::print(std::ostream& stream, bool format_inline)
{
    auto index = 0;

    while (index < this -> size) {
        auto value = this->get(index);
        
        stringstream ss; 

        if (format_inline)
            ss << this->format_text_inline(value, index);
        else
            ss << this->format_text(value);

        stream << ss.str(); 

        index++;
    }
}

为拆分代码逻辑,我新增了两个私有成员方法:

string Vector::format_text_inline(int value, int index)
{
    stringstream ss;

    if (index < (this->size - 1))
        ss << value << ", ";
    else
        ss << value;

    return ss.str();
}

string Vector::format_text(int value)
{
    stringstream ss; 

    ss << value << "\n";

    return ss.str(); 
}

上述方法目前为类的私有成员,后续考虑将文本格式化逻辑抽离为独立类,感谢所有提供帮助的开发者。


内容的提问来源于stack exchange,提问作者Pablo Fonseca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 06:57:28