c语言:文本文件操作_单词的排序

来源:百度知道 编辑:UC知道 时间:2024/06/02 08:44:14
如当前目录有文件“date1.in”,文件里放有多个英语单词(不超过1000),每个单词不超过10个字符,每行一个,单词未排序,要求将文件里的所有单词按字典顺序排序,然后将排序好的单词写入新建的文件answer.txt中(在当前目录),完成程序,实现该功能:
如date1.in文件中原文:
hello
bye
yes
程序执行后,文件answer.txt中内容如下:
bye
hello
yes

请问这题怎么做,非常感谢

#include "stdafx.h"
#include <string.h>
#include <stdio.h>
void swap(char *a,char *b)
{ char t;
t=*a;
*a=*b;
*b=t;

}
void sortstr(char s[][256],int n)
{
int i;
int j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(s[i],s[j])>0)
{
swap(s[i],s[j]);
}
}
}
}

int _tmain(int argc, _TCHAR* argv[])
{ char str[10][256];
int i;
for(i=0;i<10;i++)
{
scanf("%s ",str[i]);
}
sortstr(str,10);
for(i=0;i<10;i++)
{
printf("%s ",str[i]);
}
printf("\n");
return 0;
}
这个不是在文件里面进行操作的
文件里面使用的话自己试试改吧

#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;

int main()
{
ifstream i