文字檔案操作 單詞排序

2021-10-13 10:08:12 字數 1113 閱讀 4193

在當前目錄有檔案「case1.in」,檔案裡存放有多個(總個數不超過10000個)英文單詞(每個英文單詞不會超過10個字文字元), 每行乙個,單詞未排序。現要求,將檔案中的所有單詞按字典順序排序,然後將排序好的單詞寫入新建的檔案answer.txt中(注:檔案存放於當前目錄)。 請完成程式,實現該功能,(注意,填空題,請不要使用return 0結束,否則會影響評判而判錯)

(如case1.in檔案中原內容如下)

hello

byeyes

(程式執行後,在檔案answer.txt中內容如下)

byehello

yes整體思路:將檔案 「case1.in" 中的單詞乙個乙個讀出來,用插入排序存入陣列中,再迴圈寫入 「answer.txt」 中。

#include

"stdio.h"

#include

"string.h"

main()

strcpy

(origin[0]

,origin[n+1]

);//把讀到的單詞放到陣列第乙個}if

(strcmp

(origin[n]

, origin[n-1]

)>0)

//如果讀到的單詞排在最後,不用管,n++繼續讀取下乙個單詞if(

strcmp

(origin[n]

, origin[i]

)>0)

//讀到的單詞要放在中間

for(j=n;j>=i;j--

)//把要插入的位置之後的所有單詞都往後移一行

strcpy

(origin[i]

,origin[n+1]

);//再把讀到的單詞放到相應位置

} n++

;//讀取下乙個單詞

} fp2=

fopen

("answer.txt"

,"w");

for(i=

0;i)//因為第n個是讀取失敗時的值,所以不能等於n

fclose

(fp)

;fclose

(fp2)

;}

文字檔案操作

1 文字檔案的寫入 建立檔案流 filestream filestream new filestream c myfile file.txt filemode.create 建立寫入器 streamwriter sw new streamwriter filestream 以流的方式寫入資料 sw....

文字檔案操作

文字檔案操作 編寫乙個程式demo.py,要求執行該程式後,生成demo new.py檔案,其中內容與demo.py一樣,只是在每一行的後面加上行號以 開始,並且所有行的 符號垂直對齊。filename demo.py with open filename,r as fp lines fp.read...

C 文字檔案操作

如何向現有檔案中新增文字 usingsystem usingsystem.io classtest 如何建立乙個新文字檔案並向其中寫入乙個字串。方法可提供類似的功能。usingsystem usingsystem.io publicclasstexttofile alreadyexists.file...