【发布时间】:2019-12-05 14:15:40
【问题描述】:
我有一个程序要求用户输入一个单词,他们输入的每个单词都被添加到一个链表中。当用户输入"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。strcmp不保证返回 1 或 0。它可以返回 0 或任何其他值。检查strcmp(...) != 0。 -
@CodeCharmander 谢谢,那行得通。但我仍然不明白为什么。你能解释一下吗?
-
strcmp() 如果字符串匹配,则返回零,如果第一个字符串小于第二个字符串,则返回负数,如果第一个字符串大于第二个字符串,则返回正数。这是一个字典比较,而不仅仅是一个相等比较。
-
啊,我没有意识到它是如何工作的。我也刚google了一下。我只是认为它要么相等要么不相等,而不是它返回一个值。
标签: c if-statement while-loop linked-list strcmp