【发布时间】:2017-01-05 23:06:23
【问题描述】:
我一直在尝试使用链表做一些事情,主要是因为我想找到一种方法来确定由用户输入确定的序列长度。问题是
终端输出
[filip@filip PointerCheck]$ ./PointerCheck.o
Enter number to populate the list..
1 2 3
c
Enter number to populate the list..
Printing...
1 2 3
3
为什么会跳过列表的第二个填充?
我已经尝试了多种方法,并且我认为问题存在于 while 循环的某个地方,与 scanf();
有关
列表函数应该可以正常工作,因为来自add_to_list() 的单独调用实际上会在列表中插入一个整数,并且print_list() 会打印所有这些。所以我猜,它一定是while循环,特别是scanf();
C 代码
void user_input_list(void) {
int *input = NULL;
input = (int *) malloc(sizeof(int));
printf("Enter number to populate the list..\n");
while (scanf("%d", input)) {
add_to_list(*input, 1);
}
}
int main(int argc, char const *argv[]) {
int i = 0;
struct node *ptr = NULL;
user_input_list();
user_input_list();
print_list();
printf("%d\n", lenght_list());
return 0;
}
这是整个文件,live [link] 和pastebin
【问题讨论】:
-
一般情况下,不要使用
scanf进行用户输入。 (尝试在此站点中搜索cscanf并查看关于意外scanf行为的 5000 个重复问题。) -
您未发布的代码中是否有
scanf("%c", ...)? -
顺便说一句,你的循环条件是错误的:它应该是
scanf(...) == 1,而不仅仅是scanf(...)。scanf可能会以有趣的方式失败。 -
那个链接是垃圾。可怕的彩色和不可读的代码以及对弹出窗口的侵入性要求。
-
不要链接到外部网站。
标签: c while-loop linked-list scanf