问:有两个磁盘文件("data1.txt"和"data2.txt")各存放一行字母,今要求把这两个文件的信息合并(按字母顺序排列),输出到一个新文件"data3.txt"中.
#include <stdio.h>#include <stdlib.h>int main(){ FILE *fp1,*fp2,*fp3; char ch1[80],ch2[80],ch3[160],tmp; int i=0,j=0,m,k; fp1=fopen("D:\\CC\\data1.txt","r"); fp2=fopen("D:\\CC\\data2.txt","r"); if(fp1==NULL) { printf("Can't open file1!\n"); exit(0); } if(fp2==NULL) { printf("Can't open file2!\n"); exit(0); } while(!feof(fp1)) { ch1[i]=fgetc(fp1); i++; } ch1[i]='\0'; i=0; while(!feof(fp2)) { ch2[i]=fgetc(fp2); i++; } ch2[i]='\0'; i=0; while(ch1[i]!='\0') { ch3[i]=ch1[i]; i++; } while(ch2[j]!='\0') { ch3[i+j]=ch2[j]; j++; } ch3[i+j]='\0'; for(m=1;m<i+j;m++) for(k=0;k<i+j-m;k++) if(ch3[k]>ch3[k+1]) { tmp=ch3[k]; ch3[k]=ch3[k+1]; ch3[k+1]=tmp; } fclose(fp1);fclose(fp2); fp3=fopen("D:\\CC\\data3.txt","w"); if(fp3==NULL) { printf("open file for read error!\n"); return -1; } m=0; while(ch3[m]!='\0') { fprintf(fp3,"%c",ch3[m]); m++; } fclose(fp3); return 0;}
当data1.txt文件中输入LLOVEYOU data2.txt文件中输入YOUAREMYLOVE时 打data3.txt文件中显示的是
为什么前面有几个空格?输入其他的也一样-----前面有空格。
那么请问一下怎么解决呢?
追答用笔把数组画出来,把下标标好,细心点就改好了,排序时不要把‘\0’加进去。就ok了