前提・実現C言語に関する質問です。とある線の駅を表示する線形リストのプログラムを作成しました。
表示はすることができて駅の追加も削除もできるようにはなりました。
ですが、駅名を外部ファイルに保存して動くプログラムに変更したいです。具体的な手順としては以下の通りです。
1. プログラム起動時にファイルからデータを読み込んで画面に表示する
2. 以下の選択肢を表示して選択させ、選択に従って実行する。
・駅を追加して、結果を表示して、選択肢に戻る
・駅を削除して、結果を表示して、選択肢に戻る
・プログラムを終了する
3.プログラムを終了するとデータファイルに書き出して終了する。
この3段階です。なお、カレントディレクトリにdata.csvというファイルが用意されていると想定されていて、カンマ区切りでデータが記録されている状態を想定します。
ーーー以下はコードーーー
#include <stdlib.h>
#include <string.h>
struct station{
char name[100];
char rapid;
struct station *next;
};
void showlist(struct station *sp){//spは先頭番地よ
while((sp = sp->next)!= NULL){//spがNULL(終点)になるまで繰り返す
printf("station: %s,\trapid: %c\n", sp->name, sp->rapid);
}
}
char addstation(struct station *sp){
struct station *new;
char query_name[100];
new = (struct station *)malloc(sizeof(struct station));
printf("Insert after?: ");
scanf ("%s", query_name);
printf("Input name of new station: ");
scanf ("%s", new->name);
printf("rapid (y/n): ");
scanf ("%*c%c", &new->rapid);
//追加の作業
while(sp != NULL){//駅名の探索
if(strcmp(sp->name, query_name) == 0){
new->next = sp->next;
sp->next = new;
break;
}else{
sp = sp->next;
}
}
if(sp == NULL){//breakを踏まずにきたら,stop = NULL
printf("The station %s does not exist.\n", query_name);
exit(1);
}
}
void deletestation(struct station *sp){
char query_name[100];
struct station *tmp;
tmp = sp;
printf("Name of delete station: ");
scanf ("%s", query_name);
while(sp != NULL){
if(strcmp(sp->name, query_name) != 0){//一致しなければ続ける
tmp = sp;//今停車している駅の情報をtmpに一時保管
sp = sp->next;
}else{//名前が一致した場合
break;//ループを抜ける--> tmpの中には,1つ前の駅の情報が入っている
}
}
tmp->next = sp->next;//繋ぎかえ
}
int main(void){
struct station st0, st1, st2, st3, st4,dummy, *stop;
int flag;
dummy = (struct station){"特殊な文字列",'\0',&st0};
st0 = (struct station){"hachioji", 'y', &st1};
st1 = (struct station){"katakura", 'y', &st2};
st2 = (struct station){"aihara", 'y', &st3};
st3 = (struct station){"hashimoto", 'y', &st4};
st4 = (struct station){"sagamihara", 'y', NULL};
stop = &st0;//始発の駅のポインタ(先頭番地)をstopに代入
for(;;){//無限ループ
printf("1: add station\n 2: delete station\n 3: list\n 4: quit\n");
scanf ("%d", &flag);
switch(flag){
case 1:
printf("=== add station ===\n");
addstation(&dummy);
break;
case 2:
printf("=== delete station ===\n");
deletestation(&dummy);
break;
case 3:
printf("=== show list ===\n");
showlist(&dummy);
break;
case 4:
printf("=== quit ===");
printf("save to file hogehoge\n");
return 0;
default:
printf("select number 1 to 4\n");
break;
}
}
/* printf("=== before ===\n"); /
/ showlist(stop); */
/* // stop = &st0; /
/ addstation(&st0); */
/* stop = &st0;//始発駅にstopを移動 /
/ printf("=== after ===\n"); /
/ showlist(stop); */
return 0;
}
ーーー以上はコードーーー
よろしくお願いします
あなたの回答
tips
プレビュー