string compression for integers giving wrong output

Aug 11, 2018 at 9:21am
Hello coders,
I've been working or this for the past two days,the code is supposed to go through the string and every time there are similar characters it's supposed to increment the counter. An input of "303030404040" is supposed to print out "303403" but its printing bogus data!! please help
#include <iostream> // std::cout
#include <iomanip>
#include <string> // std::string, std::to_string
#include <stdlib.h> /* atof */
#include <math.h>
#include<sstream>
#include <cstring>
#include <vector>
#include <array>
#include <string>
#include <algorithm>
string integerrunlengthencoding(string hextext) {
int counter=1;
int length = hextext.size();
string output = "";
for(int i=0;i<length -1;i=i+2){
for(int k=1;k<length;k=k+2){
if(hextexts[i] == hextexts[i+2]){
if(hextexts[k] == hextexts[k+2] ){
counter++;
} else{
output = output + hextexts[i] + hextexts[k] + std::to_string(counter);

counter =1;
}
}

}
}
output = output + hextexts[length -1] + hextexts[length] +
std::to_string(counter);
return output.size() < hextext.size() ? output : hextext;
}
int main(){
string t = "303030404040";
cout << integerrunlengthencoding(t);
}
Last edited on Aug 11, 2018 at 9:22am
Aug 11, 2018 at 12:18pm
What's "hextexts"? From what I see in the code you haven't defined it (not hextext, HEXTEXTS)

Also look at your for loops. K+2 and I+2 jump out of the array index bound hence undefined behavior.
Topic archived. No new replies allowed.