alex01011
alex01011

Reputation: 1702

Problem with printing the correct number of same characters.RLE in C

I am having difficulties printing out the correct number of character in a RLE program. I have already made it work with arrays and Im looking for a different approach.Here is the code :

 #include <stdio.h>

int main ()
{
    char elem,elem1;
    int n=1;
    while ((elem=getchar())!=EOF && elem!='\n'){
        if ((elem1=getchar())==elem){
            n++;
        }
        printf("%d%c",n,elem);
        n=1;
    }
    printf("\n");
    return 0;
}

For example when I enter --> ttyyy the output is 2t2y1y. Already tried adding an else statement but it never actually enters the statement.Output should have been 2t3y.

Thank you in advance.

Upvotes: 2

Views: 60

Answers (1)

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Try this:

Basically, we count all characters as long as it's the same one as before. When the character changes, we print the char along with the older counter and set our counter back to 1.

  • old_elem holds the last character
  • elem holds the current character

(we set old_elem to some initial value so that we can check whether it's the first char encountered)

#include <stdio.h>

int main () {
    char elem;
    char old_elem = '$';
    int n=1;
    while ((elem=getchar())!=EOF && elem!='\n'){
        if (elem==old_elem) { 
            n++; 
        }
        else { 
            if ( old_elem!='$') { printf("%d%c",n,elem); } 
            n=1; 
        }
        old_elem = elem;
    }
    printf("%d%c\n",n,old_elem);

    return 0;
}

Example Input:

ttyyy

Output:

2t3y

Upvotes: 3

Related Questions