满意答案
zwakmh14
2013.05.31
采纳率:41% 等级:12
已帮助:6060人
#include
#include
#include
int main()
{
char user[4];
char waterNum[4];
char elecNum[4];
char inlinebuf[32];
char outlinebuf[32];
char pbuf[256];
FILE *fp1;
FILE *fp2;
int WaterNum=0;
int ElecNum=0;
int length =0;
int m=0;
int n=0;
int weishuflag=0;
int flagnum=0;
int i=0;
int j=0;
float waterPrice=0.0;
float elecPrice=0.0;
if((fp1=fopen("./input.dat","r"))==NULL)
{
printf("open input data error!\n");
return -1;
}
if((fp2=fopen("./change.dat","w"))==NULL)
{
printf("open input data error!\n");
return -1;
}
fseek(fp1,0,SEEK_END);
length = ftell(fp1);
fseek(fp1,0,SEEK_SET);
memset(pbuf,0,sizeof(pbuf));
printf("the input data length == %d\n",length);
fread(pbuf,length,1,fp1);
fseek(fp2, 0, SEEK_SET);
sprintf(outlinebuf,"住户\t\t水费\t\t电费\n");
fputs(outlinebuf, fp2);
while(length--)
{
if(pbuf[m]!='\n')
{
inlinebuf[n]=pbuf[m];
n++;
}
else
{
j = 0;
inlinebuf[n++]='\t'; //为处理每一行的最后一个数据(即用电量),需加入一个tab或空格键
inlinebuf[n] = '\0';//一行数据结束
while( inlinebuf[j] != '\0')
{
switch(flagnum)
{
case 0: //用户
if(inlinebuf[j] != ' ' && inlinebuf[j] != '\t')
{
user[i]=inlinebuf[j];
i++;
}
else
{
user[i]='\0';
flagnum++;//表示之前获取的是住户,下两个数据分别获取用水量与用电量
i=0;
}
break;
case 1: //用水量
if(inlinebuf[j] != ' ' && inlinebuf[j] != '\t')
{
waterNum[i]=inlinebuf[j];
i++;
}
else
{
waterNum[i]='\0';
weishuflag=i;//表示当前数据的位数,住户、用水量、用电量均限制为三位数以内
flagnum++;//表示下个数据获取的是用电量
if(weishuflag == 1)
{
WaterNum = waterNum[0] - 48;
}
else if(weishuflag == 2)
{
WaterNum = (waterNum[0] - 48)*10 + (waterNum[1] - 48);
}
else
{
WaterNum = (waterNum[0] - 48)*100 + (waterNum[1] - 48)*10 + (waterNum[2] - 48);
}
i=0;
weishuflag = 0;
}
break;
case 2: //用电量
if(inlinebuf[j] != ' ' && inlinebuf[j] != '\t')
{
elecNum[i]=inlinebuf[j];
i++;
}
else
{
elecNum[i]='\0';
weishuflag=i;//表示当前数据的位数,住户、用水量、用电量均限制为三位数以内
flagnum = 0;//表示一行三个数据获取完毕
if(weishuflag == 1)
{
ElecNum = elecNum[0] - 48;
}
else if(weishuflag == 2)
{
ElecNum = (elecNum[0] - 48)*10 + (elecNum[1] - 48);
}
else
{
ElecNum = (elecNum[0] - 48)*100 + (elecNum[1] - 48)*10 + (elecNum[2] - 48);
}
i=0;
weishuflag = 0;
}
break;
default:
break;
}
j++;
}
waterPrice = (float)WaterNum * 1.5;
elecPrice = (float)ElecNum * 0.5;
printf("The user == %s,waterNum == %d,elecNum == %d\n",user,WaterNum,ElecNum);//打印用户,用水量,用电量
printf("The user == %s,waterPrice == %.1f,elecPrice == %.1f\n\n",user,waterPrice,elecPrice);//打印用户,水费,电费
sprintf(outlinebuf,"%3s \t\t%4.1f \t\t%4.1f\n",user,waterPrice,elecPrice);
fputs(outlinebuf, fp2);//写入每一行数据(数据格式为 住户 + 水费 + 电费)
memset(outlinebuf,0,sizeof(outlinebuf));
memset(inlinebuf,0,sizeof(inlinebuf));
n=0; //一行数据处理结束,开始新的一行
}
m++;
}
fclose(fp1);
fclose(fp2);
return 0;
}
input.dat(每一行数据分别为住户 用水量 用电量,以空格或tab键隔开,且每行数据必须以回车结尾)
1015150
201490
3014120
401378
501460
6016105
charge.dat (输出文件格式如下)
住户水费电费
101 7.5 75.0
201 6.0 45.0
301 6.0 60.0
401 4.5 39.0
501 6.0 30.0
601 9.0 52.5
69分享举报