[英]Why is scanf() not taking my second input?
為什么從屏幕截圖可以清楚地看到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);
}
}
int value = scanf("%d", &value);
scanf返回成功讀取的項目數。 由於您正在讀取1項,並且成功將其寫入value變量,因此在返回之前覆蓋scanf寫入其中的4項。 為了清楚起見,它正在讀取第二個輸入,但是您記錄的輸入將立即被覆蓋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.