手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾对应的数据相加,三个文本的内容如下
1.若数字没有进位,可直接相加
1 #include<stdio.h>
2 int main()
3 {
4 FILE *fp1,*fp2,*fp3;
5 char ch1,ch2,ch3;
6 fp1= fopen("t1.txt","r");
7 fp2= fopen("t2.txt","r");
8 fp3= fopen("t3.txt","w+");
9
10 while((ch1 = fgetc(fp1)) !=EOF && (ch2 =fgetc(fp2)) !=EOF)
11 {
12 if(ch1 < '0' || ch1 > '9')
13 {
14 fputc(ch1,fp3);
15 }
16 else
17 {
18 ch1=ch1-'0';
19 ch2=ch2-'0';
20 ch3=ch1+ch2;
21 ch3=ch3+'0';
22 fputc(ch3,fp3);
23 }
24
25 }
26 return 0;
27 }
~
2.若数字需要进位
1 #include<stdio.h>
2 int main()
3 {
4 FILE *fp1,*fp2,*fp3;
5 char ch1,ch2,ch3;
6 fp1= fopen("t4.txt","r");
7 fp2= fopen("t5.txt","r");
8 fp3= fopen("t6.txt","w+");
9 int num1,num2,num3;
10 int flag=0; //判断数字位数
11 while((ch1 = fgetc(fp1)) !=EOF && (ch2 =fgetc(fp2)) !=EOF)
12 {
13
14 if(ch1 < '0' || ch1 > '9')
15 {
16 fputc(ch1,fp3);
17 flag=0;
18
19 }
20 else{
21 flag++;
22 if(flag == 1) //扫描到第一位数字
23 {
24 num1=0;num2=0;
25 num1=num1*10+(ch1-'0');
26 num2=num2*10+(ch2-'0');
27
28
29 }
30 if(flag ==2) //扫描到第二位数字
31 {
32 num1=num1*10+(ch1-'0');
33 num2=num2*10+(ch2-'0');
34
36 num1=num1+num2;//求和
37 num3=num1%10; //个位
38 num1=num1/10;//十位
39 ch3=num1+'0';
40 fputc(ch3,fp3); //先输出十位
41
42 ch3 =num3+'0';
43
44 ch3 =num3+'0';//再输出十位
45 fputc(ch3,fp3);
46 flag=0;
47
48
49
50 }
51
52 }
53
54 }
55 return 0;
56 }