这个程序试图读取char的2D数组(5x10)并压缩它们。这样(aaacccfeee - > 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
答案 0 :(得分:0)
试试这个:
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);
}