#include <stdio.h>
int main() {
char str[1001];
fgets(str, sizeof(str), stdin);
int i = 0;
while (str[i] != '\0') {
// Skip the newline character if it's there
if (str[i] == '\n') {
break;
}
char current = str[i];
int count = 1;
// Count consecutive occurrences
while (str[i + 1] == current) {
count++;
i++;
}
// Print the character
printf("%c", current);
// Print the count only if greater than 1
if (count > 1) {
printf("%d", count);
}
i++;
}
return 0;
}
This code reads a line of text and compresses consecutive repeated characters by printing each character once, followed by the count if it appears more than once. For example, "aaabbb" becomes "a3b3".
- The inner while loop increments `i` while counting consecutive same characters, but after the loop ends, the outer loop also increments `i` with `i++`. This causes the outer loop to skip one character after each group, potentially missing the start of the next group or going out of bounds.
- The condition `str[i + 1] == current` in the inner while loop accesses `str[i+1]` without checking if it is the null terminator `'\0'`. This could read past the end of the string if the last character is part of a repeated group.