C语言求解、、、???
发布网友
发布时间:2023-07-14 14:47
我来回答
共3个回答
热心网友
时间:2024-12-09 16:12
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
char a[5][80]={0};
char tmp[80]={0};
FILE *fp=NULL;
int i,j;
if((fp=fopen("d.txt","r"))==NULL)
{
printf("文件读取失败!\n");
exit(0);
}
for(i=0;i<5;i++)
fscanf(fp,"%s\n",a[i]);
fclose(fp);
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
{
if(strcmp(a[i],a[j])>0)
{
memset(tmp,0,80);
strncpy(tmp,a[i],strlen(a[i]));
strncpy(a[i],a[j],strlen(a[j]));
strncpy(a[j],tmp,strlen(tmp));
}
}
if((fp=fopen("D:\\e.txt","w"))==NULL)
{
printf("文件读取失败!\n");
exit(0);
}
for(i=0;i<5;i++)
fprintf(fp,"%s\n",a[i]);
fclose(fp);
}
热心网友
时间:2024-12-09 16:13
#include<stdio.h>
#include<string.h>
#define N 100
#define M 81
void sort(char s[][81],int n) {
int i,j,k;
char t[M];
for(i = 0; i < n - 1; ++i) {
k = i;
for(j = i + 1; j < n; ++j) {
if(strcmp(s[k],s[j]) > 0)
k = j;
}
if(k != i) {
strcpy(t,s[i]);
strcpy(s[i],s[k]);
strcpy(s[k],t);
}
}
}
int main(void) {
int i,n;
char str[N][M];
FILE *infp,*outfp;
infp = fopen("d.txt","rt");
outfp = fopen("e.txt","wt");
if(infp == NULL || outfp == NULL) {
printf("代开文件失败。\n");
return 1;
}
for(n = 0; !feof(infp) && n < N; ++n)
fgets(str[n++],M - 1,infp);
fclose(infp);
sort(str,n);
for(i = 0;i < n;i++) {
fputs(str[i],outfp);
puts(str[i]);
}
return 0;
}
热心网友
时间:2024-12-09 16:14
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char s[5][80],temp[80];
int i,j;
if((fp=fopen("d.txt","r"))==NULL)
{printf("Can not open file.\n");exit(0);}
for(i=0;i<5;i++)
fgets(s[i],80,fp);
fclose(fp);
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
if(strcmp(s[i],s[j])>0)
{
strcpy(temp,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],temp);
}
if((fp=fopen("e.txt","w"))==NULL)
{printf("Can not open file.\n");exit(0);}
for(i=0;i<5;i++)
fputs(s[i],fp);
fclose(fp);
return 0;
}