为什么scanf()不接受我的第二次输入?

问题描述 投票:-1回答:1

为什么scanf()没有第二次输入,因为我们可以从屏幕截图中清楚地看到它是使用为第一次输入提供的相同值?

enter image description here

#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);
    }
}
c scanf
1个回答
3
投票

int value = scanf("%d", &value);

scanf返回成功读取的项目数。因为你正在阅读1项并且它成功然后被写入值变量,所以在返回之前覆盖scanf写入的4。所以要清楚,它正在读取第二个输入,但您录制的输入会立即被覆盖。

© www.soinside.com 2019 - 2024. All rights reserved.