为什么 scanf()第二次没有输入,因为我们可以从屏幕截图中清楚地看到它使用的是为第一次输入提供的相同值?
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct NODE{
int data;
struct NODE *link;
};
struct NODE *head = NULL;
int currentSize = 0;
void print(){
struct NODE *ptr = head;
//Printing the whole linked list;
while(ptr){
printf("%d", ptr->data);
ptr = ptr->link;
}
}
void insert(int value){
//if this is the first element in the linked list
if(head == NULL){
head = (struct NODE *)malloc(sizeof(struct NODE));
head->data = value;
currentSize = 1;
return;
}
//if we traverse the linked list to the last element and then we the element
struct NODE *ptr = head;
//traversing
while(ptr->link != NULL)
ptr = ptr->link;
//new node creation and adding it to the linked list
struct NODE *new = (struct NODE *)malloc(sizeof(struct NODE));
currentSize += 1;
new->data = value;
new->link = ptr->link;
ptr->link = new;
}
int main(){
printf("Options:\n1. Insert a node\n4. Print the Linked List\n5. Enter 0 to exit\n");
printf("\nEnter your choice: ");
int choice = scanf(" %d", &choice);
printf("Value of Choice %d\n", choice);
while(choice != 0){
if(choice == 1){
printf("Enter the Value: ");
int value = scanf("%d", &value);
insert(value);
}
else if(choice == 4)
print();
else
printf("Wrong Input");
printf("\nEnter your choice: ");
choice = scanf(" %d", &choice);
printf("Value of Choice %d\n", choice);
}
}
答案 0 :(得分:3)
int value = scanf("%d", &value);
scanf返回成功读取的项目数。由于你正在阅读1项并且它成功然后被写入值变量,所以在返回之前覆盖scanf写入的4。 所以要清楚,它正在读取第二个输入,但你录制的输入会被立即覆盖。