在 C 语言中"压缩"字符数据的 2D 数组输入



这个程序正在尝试读取一个2D (5x10)字符数组,并压缩它们。这样(aaaccefeee -> a3c3f1e3)。我的输出有些问题,我不知道问题出在哪里。

代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h> 
#define SIZE1 5 
#define SIZE2 10
void compress(char data[SIZE1][SIZE2]);
int main ()
{
    int row, col;
    char qn2[SIZE1][SIZE2];
    printf("nEnter your data (5x10 of characters): n");
    for (row = 0; row < SIZE1; ++row)
        for (col = 0; col < SIZE2; ++col)
            scanf("%c", &qn2[row][col]);
    fflush(stdin);
    compress(qn2);
    return 0;
}
void compress(char data[SIZE1][SIZE2])
{
    int row, col, count = 0;
    char tempChar = data[0][0];
    printf("nThe compression output: n");
    for (row = 0; row < SIZE1; row++)
    {
        for (col = 0; col < SIZE2; col++)
        {
            if (data[row][col] == tempChar)
            {
                count ++;
            }
            else
            {
                printf("%c%d", tempChar, count);
                tempChar = data[row][col];
                count = 1;
            }   
        } printf("n");
    }
}
预期输出:

Enter your data (5x10 of characters):
aaacccdeee
fffggghiii
jjjkkklmmm
nnnooopqqq
rrrssstuuu
The compression output:
a3c3d1e3
f3g3h1i3
j3k3l1m3
n3o3p1q3
r3s3t1u3

输出结果:

The compression output:
a3c3d1
e3f3g3h1
i3j3k3l1
m3n3o3p1
q3r3s3t1u3

试试这个:

for (row = 0; row < SIZE1; row++)
{
    for (col = 0; col < SIZE2; col++)
    {
        if (data[row][col] == tempChar)
        {
            count ++;
        }
        else
        {
            printf("%c", tempChar);
            printf("%d", count);
            tempChar = data[row][col];
            count = 1;
        }   
    }
}
if(count!=0) //need to print the last sequence of repeated characters.
{
     printf("%c", tempChar);
     printf("%d", count);
}

最新更新