C小程序__从磁盘读入n个字符串, 对它们按字母大小顺序排序,然后把排好序的字符串送到磁盘文件中保持

#include "stdio.h"
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char str[3][10], temp[10];  //str是用来存放字符串的二维数组,temp是临时数组
int i, j, n = 3;
printf("请输入字符串\n");
for (i = 0; i < n; i++)
gets_s(str[i]);     //原型 gets()
for (i = 0; i < n -1; i++)    //选择法对字符串排序
{
for (j = i + 1;j < n; j++)
{
if (strcmp(str[i], str[j]) > 0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
if ((fp = fopen("file3.dat", "w"))==NULL)   //打开磁盘文件
{
printf("此文件打不开\n");
exit(0);
}
for (i = 0; i < n; i++)
{
fputs(str[i], fp);   //向磁盘文件写一个字符串,然后输出一个换行字符
putchar(10);        
printf("%s\n", str[i]);  //在屏幕上显示
}
system("pause");
return 0;
}

猜你喜欢

转载自blog.csdn.net/lanlan1266/article/details/80243723