とループ問題はだから私はちょうど練習のために、このシンプルでかなり役に立たない二重リンクリストを実装しました...ながら行います。それはアスリートと彼らがプレイするスポーツのリストです。次のように各ノードが定義されています二重リンクリスト
typedef struct node {
char* name;
char* sport;
struct node* prev;
struct node* next;
}node;
私はメイン(ノード*ヘッドがグローバルに定義される)で、リストの最初のノードを作成しました:
head = malloc(sizeof(node));
if (head == NULL) {
printf("malloc failed");
return 1;
}
head->name = "Stephen Curry";
head->sport = "Basketball";
head->next = NULL;
head->prev = NULL;
ループができるように意図されている間、このやりますユーザが端末のリストに必要な数のノードを追加する:
char names[50]; // declaring the arrays wherein the names and sports will be stored temporarily
char sports[30];
char YorN; // this will store the result from the prompt
do {
printf("name: ");
fgets(names, 50, stdin);
strtok(names, "\n"); // removing the "\n" that fgets adds so that name and sport will be printed on the same line
printf("sport: ");
fgets(sports, 30, stdin);
addNode(names, sports); // adds node to the head of the list
printReverse(); // prints the list in reverse, giving the illusion that the user is adding to the tail
printf("add a new name to the list? (Y or N): ");
YorN = fgetc(stdin);
YorN = toupper(YorN);
} while (YorN == 'Y');
最初のエントリは正常に動作します。出力:ユーザーのみがスポーツを入力することを可能にする
name: sport:
:その後
name: Reggie Miller
sport: Basketball
Stephen Curry,Basketball
Reggie Miller,Basketball
add a new name to the list? (Y or N):
ユーザは、この端末プリントを新しいノードを追加するために「Y」を選択した場合。次に、これを出力します。
name: sport: k
Stephen Curry,Basketball
,k
,k
add a new name to the list? (Y or N):
ここで、 "k"は入力されたスポーツです。 addNode()関数やprintReverse()関数の問題ではないと思いますので、簡潔にするためにそれらの記述を省略しています。しかし、誰かがそれがそれらの機能に関する問題であるかもしれないと思っている場合、または単にそれらを見たいと思うなら、私はそれらを投稿して嬉しいです。それはループのいくつかの側面、おそらく私の実装のfgetsの問題であると私には思われますか? scanfを試してみると、最初の試行でも失敗しました。どんな助けも大変ありがとう!ありがとう!
一部のコードではなく、コード全体を投稿できますか?このようにそれを理解することは困難です。 – dazzieta
'fgetc(stdin)'は 'stdin'に' '\ n''を残します。したがって、第2のループ 'fgets'はすぐに終了します。 – LPs
2回目の反復で 'fgets()'は 'Y'の後に改行文字を読み込みます。 – MikeCAT