题目描述:
文件中按文本方式存放了一段其他文章,其中有若干长度小于15的十进制或八进制数字,数字之间用“,”分开,数字内部存在且仅存在空格。八进制数以起始位“0”作为标示与十进制数区分。顺序读取这些数字将他们转变为十进制数后按从大到小的顺序排序后,输出到文件上,每个数字一行。
输入描述:
_235_,34__2,_043_1_,1_3 (_代表空格)
输出描述:
342
0431
235
13
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void stringToInt(char data[][15],int turn[],int num);
void sort(char data[][15],int turn[],int num);
int main(){
char data[50][15];
int turn[50];
FILE *fp,*fa;
int i=0,j=0,s=0;
char temp;
if((fp=fopen("D:\\2019Post\\pat\\pat\\data2009.txt","r"))==NULL){
printf("can not open the file");
exit(0);
}
while(!feof(fp)){
temp=fgetc(fp);
if(temp>='0'&&temp<='9'){
data[i][j]=temp;
j++;
}
if(temp==','){
data[i][j]='\0';
i++;
j=0;
}
}
data[i][j]='\0';
i++;
fclose(fp);
stringToInt(data,turn,i);
sort(data,turn,i);
if((fa=fopen("D:\\2019Post\\pat\\pat\\data2009_out.txt","w"))==NULL){
printf("can not open the file");
exit(0);
}
for(;s<i;s++){
fprintf(fa,"%s\n",data[s]);
}
fclose(fa);
}
void stringToInt(char data[][15],int turn[],int num){
int i,j,x=0;
for(i=0;i<num;i++){
if(data[i][0]=='0'){
for(j=1;data[i][j]!='\0';j++){
x=x*8+data[i][j]-'0';
}
turn[i]=x;
x=0;
}else{
for(j=0;data[i][j]!='\0';j++){
x=x*10+data[i][j]-'0';
}
turn[i]=x;
x=0;
}
}
}
void sort(char data[][15],int turn[],int num){
int i,j;
int temp;
char str[15];
for(i=1;i<num;i++)
for(j=0;j<num-i;j++){
if(turn[j]<turn[j+1]){
temp=turn[j];
turn[j]=turn[j+1];
turn[j+1]=temp;
strcpy(str,data[j]);
strcpy(data[j],data[j+1]);
strcpy(data[j+1],str);
}
}
}
体会:
1、注意数字字符串转整数的方法。
2、处理数中带有其他字符的方法是先做预处理,将每个数中的纯数字提取出来。