Q:

Strange output for vector of chars

Background:
This questions comes from the Daily Coding problem #29.

Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.

Attempted Solution:
#include <iostream>
#include <string>
#include <vector>

std::vector<char> run_length(std::string str)
{
    std::vector<char> result;
    if (str.empty() || str.size() == 1)
    {
        const char *ch = str.c_str();
        result.push_back(*ch);
        return result;
    }

    int count = 1;
    for (int i = 1; i < str.size(); ++i)
    {
        if (str[i] == str[i - 1])
            count++;
        else
        {
            if (count > 1)
            {
                char ch = count;
                result.push_back(ch);
            }
            result.push_back(str[i - 1]);
            count = 1;
        }
    }
    if (count > 1)
    {
        char ch = count;
        result.push_back(ch);
    }
    result.push_back(str[str.size() - 1]);

    return result;
}

int main()
{
    std::string str = "AAAABBBCCAA";
    auto result = run_length(str);

    for (auto it : result)
        std::cout << it << " ";

    std::cin.get();
}

Expected Output:
4A3B2C1D2A

Actual Output:
 A  B  C  A  

Question:
Why do I get these strange characters for the actual output? I believe the logic of my approach should work to solve the problem but yet I get these characters that I have not seen before. Any suggestions are greatly appreciated.

A:

The line
char ch = count;

is not correct.
If count is 4, then ch is initialized to a character that is encoded by the integer value 4. You need to get the character that represents the digit. You need '4'. You can use the following to get the digit from count.
char ch = '0' + count;

However, if count is greater than 9, that won't work. You'll have to come up with a different strategy if you expect count to be greater than 9.

