jeudi 5 décembre 2019

My if statement is doing the opposite of what I want it to do - linked lists in C

I have a program that asks the user to input a word, and each word they enter is added to a linked list. When the user enters "END" the program is supposed to list all the nodes.

My problem is that the program only adds the word "END" into the list, and when the user enters anything else, the else condition is triggered: all the items in the list are printed out, but all these words are just "END".

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
  char word[32];
  struct node *next;
};

int main() {
  struct node *head = NULL, *cur = NULL;
  char input[32];

  while(1) {
    cur = malloc(sizeof(struct node));

    printf("Enter words: ");
    scanf("%s", input);

    if (strcmp(input, "END") == 0) {
      cur->next = head;
      strcpy(cur->word, input);
      head = cur;
    } else {
      struct node *iter = head;

      while (iter != NULL) {
        printf("Contents: %s\n", iter->word);
        iter = iter->next;
      }
    }
  }
}

By making the if statement check if the condition == 1 it just makes the user just keep entering words, regardless what the user inputs, such as"END".

Any help would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire