0

I am doing a problem where we have to encode a string. The problem is as follows:

Given a string, Your task is to complete the function encode that returns the run length encoded string for the given string. Eg. if the input string is "wwwwaaadexxxxxx", then the function should return "w4a3d1e1x6". You are required to complete the function encode that takes only one argument the string which is to be encoded and returns the encoded string.

char *encode(char *src)
{     
    char previous=src[0];

    int i=0;
    int count=0;
    string s="";


    for(i=0;src[i]!='\0';i++){
        if(previous==src[i])
            count++;
        if(previous!=src[i]){
            s=s+previous+to_string(count);
            count=1;
            previous=src[i];
        }
        //cout << i << " " ;
        if(src[i+1]=='\0'){
            s+=previous+to_string(count);
        }

    }

  // line for reference 


    // cout << " " ;




    return &s[0];
}     


input :
hchzvfrkmlnozjk

correct output(as given by the website) : 
h1c1h1z1v1f1r1k1m1l1n1o1z1j1k1

my output : 
°¼!

If I comment out the cout statement then the correct output is printed except it has a space in front of it.

I have also tried copying the string s contents to the src contents like this by changing the code after line for reference to

for(i=0;i!='\0';i++){
        src[i]=s[i];
    }


    return src;
}     

Now the output is the original input string i.e "hchzvfrkmlnozjk"

The driver program is not accessible to us and is done by the website we have to just complete the function.

Why is cout changing the output and in the second case why is the original contents of src not being overridden with contents of string s? Is there any way to solve this?

The problem can be found here: http://www.practice.geeksforgeeks.org/problem-page.php?pid=700243

  • When these things happen you most likely have Undefined Behavior in your code. – drescherjm Dec 02 '16 at 18:41
  • Recommend editing your question to add your test cases and test driver code. Also recommend you invest some time in learning to use the debugging software that likely came with whatever development environment you are using. – user4581301 Dec 02 '16 at 18:47

0 Answers0