Search code examples
c++compressionrun-length-encoding

run-length encoding using C++


I have a text file with a string which I'd like to encode.

Let's say it is: aaahhhhiii kkkjjhh ikl wwwwwweeeett

and here is the code:

void Encode(std::string &inputstring, std::string &outputstring)
{
    for (int i = 0; i < inputstring.length(); i++) {
        int count = 1;
        while (inputstring[i] == inputstring[i+1]) {
            count++;
            i++;
        }
        if(count <= 1) {
            //std::cout << inputstring[i] << "";
            outputstring += inputstring[i];
            outputstring += "";
        } else {
            //std::cout << inputstring[i] << count;
            outputstring += inputstring[i];
            outputstring += count;
        }
    }
}

output should be: 3a4h3i 3k2j2h ikl 6w4e2t

Characters or white spaces with less (or equal) than one character get just printed out - no change.

So far so good and code is working.. actually.

When I use std::cout in if and else - then it is showing me the output like above. So perfect.

BUT, I'd like to hand over the result to the parameters (std::string &outputstring) and print the result in the main method.

But it is printing ONLY the if statement not else statement.

Can someone help me with this matter?


Solution

  • Your problem was with the line outputstring += count;. An integer is interpreted as a character code when assigning it to a string. You don't want the character with the character code count, but you want to convert the number count to a string, so you should use outputstring += std::to_string(count);