gpt4 book ai didi

使用 ScanF 在循环中创建新变量

转载 作者:行者123 更新时间:2023-11-30 15:36:07 25 4
gpt4 key购买 nike

我正在尝试为 C 中的优先级队列收集用户数据。当我有一个循环执行多个 scanf 来收集输入时。我的问题是,当我最终从队列中弹出我的值时。所有元素的值(value)相同。这是我的例子:

queue_t *q = create();

//The count is just a temporary solution to a break condition.
//Just used for testing

int count = 0;
while(1){

printf("\nPlease Enter A Task: \n");
char* a;
scanf("%s", &a);

printf("\nPlease give your task a priority ranking between 0-(less important) and 10-(most important) : \n");
int rank;
scanf("%d", &rank);

item_t item;
item.value = &a;
item.rank = rank;

insert(q, item);
count++;

if(count == 5)
break;
}

所以这个循环了 5 次。如果我输入:test1、test2、test3、test4、test5。当它最终在后面的代码中弹出并打印时,它会打印:test5 test5 test5 test5 test5

如何有效地使用循环来收集输入而不覆盖先前输入的地址? (如果这就是问题所在)

我的结构是:

typedef struct i {
void *value;
float rank;
} item_t;

最佳答案

要解决您的问题,应该分配 item.value 然后写入

while(1) {

printf("\nPlease Enter A Task: \n");
item_t item;
item.value = (char *)malloc(100);
// scanf("%s", item.value);
fgets(item.value, sizeof (item.value), stdin);

printf("\nPlease give your task a priority ranking between 0 -(less important) and 10-(most important) : \n");
scanf("%f", &item.rank);

insert(q, item);
count++;

if(count == 5)
break;
}

关于使用 ScanF 在循环中创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22677332/

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