【问题标题】:Why the behaviour of string differs here? Why the first for loop print nothing and second print the output correctly为什么字符串的行为在这里不同?为什么第一个 for 循环不打印,第二个正确打印输出
【发布时间】:2015-06-09 23:29:58
【问题描述】:

在这个String 长度编码算法中,我无法理解字符串的奇怪行为。谁能解释一下字符串的用法?下面的第一个for loop 什么都不打印,而第二个打印正确。我尝试使用大小、长度和调整大小,但第一个 for loop 仍然没有打印任何内容。

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    string str, newstr;
    str="aabcccccaaa";
    newstr[0]=str[0];
    cout<<str;
    int j = 1;
    for (int i =0; i<str.length(); i++)
    {
            int count =1;
            while(i+1 != str.length() && str[i] == str[i+1])
            {
                count++; i++;
            }
            newstr[j] = '0'+count;
            if(i+1 != str.length())
            {   newstr[j+1] = str[i+1];
                j=j+1;
            }
            j=j+1;
    }
    cout<<"\nRun String:";
    for(int i =0; i<newstr.size(); i++) // First For loop.
        cout<<newstr[i];
    for(int i=0; i<j; i++) // Second For loop.
        cout<<newstr[i];

    return 0;
}

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    newstr 是一个空字符串。当你这样做时

    newstr[0]=str[0];
    

    或者这个

    newstr[j] = '0'+count;
    

    或者这个

    newstr[j+1] = str[i+1];
    

    您通过越界访问其存储来调用未定义的行为。在那之后所有的赌注都取消了。首先,修复这些错误。

    【讨论】:

    • 理想情况下他会使用push_back 或其他东西而不是使用[],但添加newstr.resize(str.size()); 会使他的程序成功运行。
    猜你喜欢
    • 2019-12-23
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多