#include <stdio.h>
int main() {
char str[1001];
fgets(str, sizeof(str), stdin);
int i = 0;
while (str[i] != '\0' && str[i] != '\n') {
char current = str[i];
int count = 1;
while (str[i + 1] == current && str[i + 1] != '\0') {
count++;
i++;
}
printf("%c", current);
if (count > 1) {
printf("%d", count);
}
i++;
}
return 0;
}
This code reads a line of text and compresses it by replacing consecutive repeated characters with the character followed by the count. For example, "aaab" becomes "a3b". It uses two nested loops: the outer loop moves through the string, and the inner loop counts how many times the current character repeats consecutively.
- The inner loop increments `i` while counting repeats, but after the inner loop ends, the outer loop also increments `i` with `i++`. This means `i` is advanced twice for the last character of a repeated group, potentially skipping a character or going past the end of the string.
- The condition `str[i + 1] == current` in the inner loop does not check for the newline character `'\n'` that `fgets` includes, so if the input ends with a repeated character followed by newline, the newline might be treated as part of the repetition.