Online Compiler C

#include <stdio.h> int main() { char s[1001], t[1001]; int len = 0; int n = 0; int x=1; while ((s[n] = getchar()) != EOF) { n++; } scanf("%[^\n]", s); for (int i = 0; i < n; i++) { while (s[i + 1] != s[i]) { printf("%c",s[i]);} while (s[i + 1] == s[i]) { x++; printf("%c%d",s[i]x) } } return 0; }
这段代码试图实现一个字符串压缩功能,但存在多个问题。代码先尝试用getchar读取输入到数组s,然后又用scanf读取一次,导致输入被覆盖。主要逻辑是遍历字符串,当遇到连续相同字符时计数并输出字符和次数,但实现有误。

- 第一个while循环用getchar读取输入,但随后又用scanf读取,导致第一次读取的数据被覆盖。应该只使用一种输入方式。
- 在第二个while循环中,`printf("%c%d",s[i]x)`缺少逗号,这是语法错误。同时,当遇到连续相同字符时,应该先统计完所有连续字符再输出,而不是每遇到一个就输出一次。