c - 我的 if 语句与我想要的相反

标签 c if-statement while-loop linked-list strcmp

我有一个程序,要求用户输入一个单词,他们输入的每个单词都会添加到一个链接列表中。当用户输入“END”时,程序应该列出所有节点。

我的问题是程序只将单词“END”添加到列表中,当用户输入其他内容时,会触发else条件:列表中的所有项目都被打印出来,但所有这些词都只是“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;
      }
    }
  }
}

通过让 if 语句检查条件 == 1 ,它只会让用户继续输入单词,无论用户输入什么,例如“END” .

任何帮助将不胜感激。

最佳答案

if语句中的条件

if (strcmp(input, "END") == 0)

表示存储在数组input中的字符串等于字符串文字"END"。因此,如果数组包含字符串“END”,您将在列表中插入一个新节点。

此外,您必须在此检查之后而不是之前为新节点分配内存。否则会出现内存泄漏。

请注意,您有一个无限循环。

并且您需要释放所有分配的内存。

你的意思似乎是这样的

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

#define N   32

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

int main(void) 
{
    struct node *head = NULL;
    char input[N];

    printf( "Enter words: " );

    while ( scanf( "%31s", input ) == 1 )
    {
        char tmp[N];

        size_t i = 0;

        while ( ( tmp[i] = toupper( ( unsigned char )input[i] ) ) != '\0' ) ++i;

        if ( strcmp( tmp, "END" )  == 0 ) break;

        struct node *current = malloc( sizeof( struct node ) );
        strcpy( current->word, input );
        current->next = head;
        head = current;
    }

    for ( struct node *current = head; current != NULL; current = current->next )
    {
        printf( "%s -> ", current->word );
    }

    puts( "NULL" );

    while ( head != NULL )
    {
        struct node *current = head;
        head = head->next;
        free( current );
    }

    return 0;
}

程序输出如下所示

Enter words: Jackson Jake Hello end
Hello -> Jake -> Jackson -> NULL

关于c - 我的 if 语句与我想要的相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59197099/

相关文章:

c - 我什么时候应该使用 calloc 而不是 malloc

java - Eclipse不允许我在尝试验证用户输入时使用else语句

python - 在 python 中使用带有可变字符串的条件

c++ - 第一学期 CS 学生需要帮助理解 While 循环中的语句

c - 链表的自由行为

检查数字中的偶数或奇数 `1` 位

c - 为什么我会收到段错误 : 11?

python - 如何根据程序中的用户输入给出错误消息?

c - while循环,当它运行 "string"数据时,如何用特定的单词或字母中止它?

c++ - 使用getline解析和存储变量