一个小问题,但很奇怪,不晓得哪里不对
问题如下:在main函数里,第一次输入choice的值是正常的,但第二次循环输入choice时,不管我输入什么,单步调试的时候choice的值都变成了-2.。。为什么?
#include"stdlib.h"
#include"stdio.h"
//函数 压缩
void compression(char a[],char b[])
{
char temp[1],x;
int count=0;
FILE *fp,*fp2;
if( (fp=fopen(a,"rb"))==NULL )
{
printf("can not open this file!\n" );
exit(0);
}
fgets(temp,2,fp);
rewind(fp);
fp2=fopen(b,"wb");
while(fread(&x,1,1,fp))
{
if( temp[0]==x )
{
count=count+1;
}
else
{
fprintf(fp2,"%d",count);
fprintf(fp2,"%c",temp[0]);
count=1;
temp[0]=x;
}
}
fprintf(fp2,"%d",count);
fprintf(fp2,"%c",temp[0]);
printf("\n");
fclose(fp2);
fclose(fp);
return;
}
//函数解压
void compressed(char a[],char b[])
{
char x;
int count,i;
FILE *fp2,*fp3;
if( (fp2=fopen(a,"rb"))==NULL )
{
printf("can not open this file!\n" );
exit(0);
}
fp3=fopen(b,"wb");
while(fscanf(fp2,"%d%c",&count,&x)!=-1)
{
for(i=0;i<count;i++)
{//printf("%c",x);
fprintf(fp3,"%c",x);
}
}
fclose(fp3);
fclose(fp2);
}
void main()
{
int choice;
struct stu
{
char film[20];
char ys[20];
char jy[20];
} *pf;
printf("******************************\n");
printf("*** 菜 单 ***\n");
printf("*** 1 文件的压缩 ***\n");
printf("*** 2 文件的解压 ***\n");
printf("*** 3 结束程序 ***\n");
printf("******************************\n");
while(1)
{
printf("\n请输入所选功能的代码:");
fflush(stdin);
scanf("%d",&choice);
printf("\n");
switch(choice)
{
case 1 ://压缩
pf=(struct stu*)malloc(sizeof(struct stu));
fflush(stdin);
printf("请输入被压缩的文件的文件名:");
gets(pf->film);
printf("\n");
printf("请输入被压缩后的文件的文件名:");
gets(pf->ys);
compression(pf->film,pf->ys);
printf("文件压缩已完成\n");
free(pf);
printf("\n");
break;
case 2 ://解压
pf=(struct stu*)malloc(sizeof(struct stu));
fflush(stdin);
printf("请输入被解压的文件的文件名:");
gets(pf->ys);
printf("\n");
printf("请输入被解压后的文件的文件名:");
gets(pf->jy);
compressed(pf->ys,pf->jy);
printf("文件解压已完成\n");
free(pf);
printf("\n");
break;
}
/*printf("\n请输入所选功能的代码:");
fflush(stdin);
scanf("%d",&choice);
printf("\n");*/
}
}
[解决办法]
结贴吧,编译器的问题。
[解决办法]
在每个最后不带\n的printf后面加fflush(stdout);
在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin);
另外请检查scanf的返回值。