我想编写一个代码,例如将此文本:“aaaaaaabbbb”转换为:“a7b4”。 它应该从一个文件读取并写入另一个文件。这是代码的错误部分,我无法使其工作。 Ty求助..
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);
答案 0 :(得分:2)
fputs(poc, fout);
^^^
poc
是整数类型。 fputs()
的第一个参数是字符串类型。你不能混合和匹配这两者。
请改为使用:
fprintf(fout, "%d", poc);
但请记住,当计数大于10时,输出有时可能不明确。例如,输出:
12345
可能代表1 x 2, 3 x 45
或1 x 23, 4 x 5
(例如)。
答案 1 :(得分:2)
这是我的代码(不是最佳解决方案)来解决评论问题....希望它有助于您自己的代码和程序!!
#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%d\n",str,nb);
fclose(fileto);
fclose(file);
}
return 0;
}