darthsidious
darthsidious

Reputation: 3081

Insert integer in an array C++

I wrote the following code to convert string of type 'aaadddbbbccc' to 'a3d3b3c3' :

#include <iostream>
#include <string.h>
using namespace std;

    void stringCompression(char *str,char *newStr){
        int a[256] = {0};
        int newCount = 0;
        for(int i = 0; i < strlen(str) ; i++){
            int j = str[i];
            if (a[j] == 0 && strlen(newStr) <= strlen(str)){
                a[j] = 1 ;
                newStr[newCount] = str[i];
                newCount++;
                int count = 0;
                for (int n = i; n < strlen(str); n++){
                    if(str[i] == str[n]){
                        count = count + 1;
                    }
                }
                newStr[newCount] =(char) count;
                newCount++ ;
            } else if (strlen(newStr) > strlen(str)){
                strcpy(newStr,str);
            }
        }
    }

    int main() {
        char str[] = "abcdabcdabcd";
        char *newStr = new char[strlen(str)+1];
        stringCompression(str,newStr);
        cout << newStr;
        return 0;
    }

My problem is at step

newStr[newCount] =(char) count;

even though it is inserted but the output is not a3b3c3d3 but a*squarebox*b*squarebox*c*squarebox*d*squarebox*. squarebox being 2*2 matrix with one value as the number that is desired. I am using eclipse IDE. . I would really appreciate your help. How can I correct this. Am I using the correct approach?

Thanks in advance.

Upvotes: 0

Views: 109

Answers (2)

Jan R&#252;egg
Jan R&#252;egg

Reputation: 10055

The problem is that

newStr[newCount] =(char) count;

converts the number "count" into the character corresponding to that number according to the ascii table (http://www.asciitable.com/), which is "end of text" for "3", that does not correspond to any number.

You should convert "count" into a string instead. See here for example: Easiest way to convert int to string in C++

However, be aware that it might be longer than one digit, for example if count is "11", it will take two letters in string representation.

Upvotes: 1

PankajM
PankajM

Reputation: 417

Hey you have to use http://www.cplusplus.com/reference/cstdlib/itoa/ to convert integer to char string

Upvotes: 0

Related Questions