gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:34:46 27 4
gpt4 key购买 nike

为什么 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);
}
}

最佳答案

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

scanf 返回成功读取的项目数。由于您正在读取 1 项并且成功,然后将其写入 value 变量,从而覆盖 scanf 在返回之前写入的 4 项。因此,需要明确的是,它正在读取第二个输入,但您记录的输入会立即被覆盖。

关于c - 为什么 scanf() 不接受我的第二个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com