为什么这个函数打印的是x而不是1
Why is this function printing an x instead of 1?
我编写了一个用于行程编码的小程序。
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);
}
相关文章:
- 如何使用重新定义的打印函数打印Lua表?
- 从函数打印 CLI 帮助消息后,我应该如何干净地退出 C++ 程序?
- 使用成员函数打印对象
- 函数打印输出C 的错误
- 函数打印奇怪的值.C++
- Std::copy 和 std::ostream_iterator 使用重载函数打印值
- C++ 通过函数打印出 2D 数组
- 使用模板函数打印智能指针矢量
- C 是否可以使用宏从称呼的地方进行类函数打印
- infix/postfix/prefix程序.想要使用我的printresult()函数打印结果.需要帮助获得输出
- 从 Main 中的双指针函数打印出指针数组
- 如何使用递归函数打印节点树
- 重载函数打印
- 尝试通过函数打印时"Garbage" 2D 数组中的值
- 如何通过包含要打印的字符串的类函数打印异常
- 从函数C++打印出 2D 数组
- 如何通过wprintf函数打印uint32_t变量值
- 为什么我的函数打印地址而不是数组的内容
- 为什么这个函数打印的是x而不是1
- 将函数打印到输出文件