我想写一个代码,将例如这个文本:"aaaaaaabbb"转换为:"a7b4"。它应该从一个文件读取并写入另一个文件。这是代码的错误部分,我无法使其工作。泰寻求帮助..
fread(&fx,sizeof(fx),1, fin); // read first character
while(!feof(fin))
{
fread(&z, sizeof(z),1, fin); //read next characters
if(z!=fx) { fputs(fx, fout);
fputs(poc, fout);
poc=1; // if its different count=1
fx=z; // and z is new character to compare to
}
else poc++;
}
fputs(fx, fout);
fputs(poc, fout);
这是我
的代码(不是最佳解决方案)来解决注释问题....希望它对您自己的代码和程序有所帮助!
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
/* file is a pointer to the file input where to read the line */
/* fileto is a pointer to the file output where we will put */
/* the compressed string */
FILE* file, *fileto;
file=fopen("path_to_input_file","r");
fileto=fopen("path_to_output_file","w");
/* check if the file is successfully opened */
if (file!=NULL)
{
/* the str will contain the non compressed str ing */
char str[100];
/* read the non compressed string from the file and put it */
/* inside the variable str via the function fscanf */
fscanf(file,"%[^n]s",str);
/* the variable i will serve for moving character by character */
/* the variable nb is for counting the repeated char */
int i=0,nb=1;
for (i=1;i<strlen(str);i++)
{
/* initialization */
nb=1;
fprintf(fileto,"%c",str[i-1]);
/* loop to check the repeated charac ters */
while (i<strlen(str) && str[i]==str[i-1])
{
i++;
nb++;
}
fprintf(fileto,"%d",nb);
}
/* handle the exception for the last character */
if(strlen(str)>=2 && str[strlen(str)-1]!=str[strlen(str)-2])
fprintf(fileto,"%c%d",str[strlen(str)-1],1);
/* handle the string when it is composed only by one char */
if(strlen(str)==1)
fprintf(fileto,"%s%dn",str,nb);
fclose(fileto);
fclose(file);
}
return 0;
}
fputs(poc, fout);
^^^
poc
是整数类型。要fputs()
的第一个参数是字符串类型。您不能将两者混合搭配。
请考虑改用:
fprintf(fout, "%d", poc);
但请记住,当计数大于 10 时,输出有时可能不明确。例如,输出:
12345
可能代表1 x 2, 3 x 45
或1 x 23, 4 x 5
(例如)。