为什么这个函数打印的是x而不是1

Why is this function printing an x instead of 1?

本文关键字:函数 打印 为什么      更新时间:2023-10-16

我编写了一个用于行程编码的小程序。

void runLengthEncoding (string& str)
{
    int k=0;
    int count =1;
    for (unsigned i=1, count=1; i<str.size(); ++i)
    {
            if ( str[i] == str[k])
            {
                    count +=1;
            }
            else
            {
                    str[++k] = count+'0';
                    str[++k] = str[i];
                    count = 1;
            }
    }
    str[++k] = count + '0';
    str.resize(k);
}

当我使用调用此函数时

string s = "wwwwaaadexxxxxx";
runLengthEncoding (s);
cout << endl << s;

正在打印-"w4a3d1e1x"它应该打印-"w4a3d1e1x6"

我的疑问是为什么它没有打印最后一次计数?

而不是使用

str.resize(k) 

我需要使用

str.resize(k+1);

如果您为计数初始化而删除,并正确调整大小,则会得到:

void runLengthEncoding (string& str)
{
    int k=0;
    int count =1;
    for (unsigned i=1; i<str.size(); ++i)
    {
        if ( str[i] == str[k])
        {
            count +=1;
        }
        else
        {
            str[++k] = count+'0';
            str[++k] = str[i];
            count = 1;
        }
    }
    str[++k] = count + '0';
    str.resize(++k);
}