我有一个5 x 10 char
矩阵,我想压缩它就像运行长度编码一样。
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
scanf("%c", &matrix2[i][j]);
printf("\n");
compress(matrix2);
break;
void compress(char data[SIZE1][SIZE2])
{
int row, column, count=1;
for (row = 0; row < SIZE1; row++)
{
for (column = 0; column < SIZE2; column++)
{
if (data[row][column] == data[row][column + 1])
{
count++;
}
else
{
printf("%c%d", data[row][column], count);
count = 1;
}
}
}
}
这是我的代码,但我不明白为什么我的输出总是在前面有1。 输入:
aaabbbcccd
aabbccddee
aaaaaaaaaa
abcabcabca
aaabbbcccc
输出:
a3b3c3d1
1a2b2c2d2e2
1a10
1a1b1c1a1b1c1a1b1c1a1
1a3b3
预期产出:
a3b3c3d1
a2b2c2d2e2
a10
a1b1c1a1b1c1a1b1c1a1
a3b3c4
答案 0 :(得分:2)
它也在计算换行符。
答案 1 :(得分:0)
我相信评论者提出了这样的改变:
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
scanf("%c", &matrix2[i][j]);
printf("\n");
compress(matrix2);
break;
void compress(char data[SIZE1][SIZE2])
{
int row, column, count=1;
for (row = 0; row < SIZE1; row++)
{
for (column = 0; column < SIZE2; column++)
{
if (data[row][column] == data[row][column + 1])
{
count++;
}
else
{
if (data[row][column] != '\n')
{
printf("%c%d", data[row][column], count);
count = 1;
}
}
}
}
}
答案 2 :(得分:0)
更改数据条目。它处理\n
和错误检测。
printf("Enter your data (%dx%d) of characters: \n", SIZE1, SIZE2);
for (i = 0; i < SIZE1; i++) {
char buffer[(SIZE2 + 2)*2]; // Consider IO buffers 2x the needed size
if (fgets(buffer, sizeof buffer, stdin) == NULL)
Handle_EndOfFileOrIOError();
size_t len = strlen(buffer);
if (len != SIZE2+1 || buffer[len-1] != '\n')
Handle_UnexpectDataLengthError(buffer, len);
for (j = 0; j < SIZE2; j++) {
matrix2[i][j] = buffer[j];
}
// or simply memcpy(matrix2[i], buffer, SIZE2);
printf("\n");
compress(matrix2);
break;