作者skyinmoon86 (阿詠~^^萬歲)
看板C_and_CPP
標題[問題] C程式的問題..
時間Thu Oct 1 20:33:10 2009
題目如下:
Write a program to read a series of names, one per line, from standard input
,and write out those names spelled in reverse order to a file called file1.
Write another program to read the names in from file1, reverse them again,
sort them, and write them out to a file called file2.
第一題我已經做完了..
第一題的程式碼如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *file;
int i=0;
int j=0;
int k=0;
char filename[20];
char name[20];
char name2[20];
printf("Enter the name of the file: ");
gets(filename);
file=fopen(filename,"w");
if(file!=NULL){
printf("Enter several names (Enter EOF to end input):\n");
while(!feof(stdin)){
gets(name);
j=0;
for(i=(strlen(name)-1);i>=0;i--){
name2[j++]=name[i];
}
name2[j]='\0';
fprintf(file,"%s\n",name2);
for(k=0;k<19;k++){
name[k]=0;
}
}
}
fclose(file);
return 0;
}
第一題算是完成了..
但是第二題我不會排序..
程式碼如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *file;
FILE *file2;
char name[20]={0};
char name2[20]={0};
int i=0;
int j=0;
file2=fopen("file2","w");
if((file=fopen("file1","r"))!=NULL){
while(!feof(file)){
fread(&name,sizeof(name),1,file);
if(name!=0){
j=0;
for(i=(strlen(name)-1);i>=0;i--){
name2[j++]=name[i];
}
name2[j]='\0';
fwrite(&name2,sizeof(name2),1,file2);
}
}
}
fclose(file2);
fclose(file);
return 0;
}
請大家幫幫我= =
我的時間快到了..
謝謝大家
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.130.138.118
1F:推 tomore:這要用到二維的動態配置了 不然也不知道file裡有幾筆名字 10/01 20:57
2F:→ skyinmoon86:那我慘了= = 10/01 21:01
3F:→ MOONRAKER:你好像已經有兩個同學了? 10/01 21:29
4F:→ MOONRAKER:抱歉…原來你就是那位同學 XD 10/01 21:29
5F:推 VictorTom:老實說, 連著三篇, 很想說請不要用沒有意義的標題.... 10/01 21:33
6F:→ VictorTom:而且還三個都不一樣串接都不能串, 實在莫名其妙.... 10/01 21:33
7F:→ VictorTom:二維動態配置或者Linked-List都可以處理不知道幾筆資料 10/01 21:35
8F:→ VictorTom:的問題, 再不然就放大絕, 先問清楚測資範圍, 再開一個 10/01 21:35
9F:→ VictorTom:夠大的陣列放所有資料. 排序我在第一篇就推過了, 如果 10/01 21:36
10F:→ VictorTom:數字會排序, 那字串比大小用strcmp比, 字串copy用strcpy 10/01 21:36
11F:→ VictorTom:做; 如果排序不懂, 就先search找排序的演算法然後套進 10/01 21:37
12F:→ VictorTom:字串的比較和copy來排.... 10/01 21:38
13F:推 legnaleurc:用 linked list 可以直接用 insertion sort 10/01 21:43
14F:推 softwind:說真的 不方便allocate mem嗎??? 10/01 23:43
15F:→ james732:先用個巨大陣列頂著用吧... 10/01 23:45
16F:→ softwind:你時間到了 就會有版友寫給你 放心 OK的 10/02 01:15