-2

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?

Sayed Sohan
  • 1,385
  • 16
  • 23
liasis
  • 21
  • 1
  • 5
  • 2
    ***Can someone help me with this matter?*** My word of advice is to learn to use your debugger. If you had set a breakpoint in the else you should have seen that it was called. Even using a cout could of helped as in this: [https://ideone.com/ahDvox](https://ideone.com/ahDvox) – drescherjm Feb 16 '20 at 14:13
  • Also put `outputstring += inputstring[i];` after `outputstring += std::to_string(count);` – Sayed Sohan Feb 16 '20 at 14:18
  • @drescherjm you are right. But I am still a beginner though. Sorry, but I appreciate your help. Thank you! – liasis Feb 16 '20 at 14:19
  • 1
    I tell you this because its essential skill you will need to master to be an effective programmer. I debug regularly and I have programmed in `c++` since the 1990s. – drescherjm Feb 16 '20 at 14:21

1 Answers1

1

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);

Arno Deceuninck
  • 320
  • 3
  • 10
  • holy sh##t.. this is exactly what I was looking for. Thanks man! I appreciate your help. Thanks! – liasis Feb 16 '20 at 14:15