Почему scanf () не принимает мой второй ввод? - PullRequest
0 голосов
/ 24 мая 2018

Почему 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);
    }
}

1 Ответ

0 голосов
/ 24 мая 2018

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

scanf возвращает количество успешно прочитанных элементов.Поскольку вы читаете 1 элемент, и он успешно записывается в переменную value, перезаписывает 4, которую scanf записал в него перед возвратом.Итак, чтобы быть понятным, он читает 2-й вход, но записанный вами вход немедленно перезаписывается.

...