gpt4 book ai didi

c -++i 在 while 循环中只改变一次

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:18 24 4
gpt4 key购买 nike

我正在为我的嵌入式 C 类(class)布置作业,但我遇到了一个我似乎无法解决的问题。我的问题是 ++i 只会改变一次。循环第一次运行 i 将是 0,第二次 i1 但之后 i 将始终为 1,无论循环循环了多少次。任何人都知道问题可能是什么?我输入 printf("%d\n", i); 只是为了查看 i 是否更改。

void addCar() {
char choice = 'y';
int i = 0;
while((choice == 'y' || choice == 'Y') && i < MAX_CAR) {
printf("Make: ");
scanf("%s", fleet[i].make);

getDate(1, i);

getDate(2, i);

printf("Purchaseprice: ");
scanf("%lf", &fleet[i].purchasePrice);

++i;
printf("%d\n", i);
printf("Do you want to add another car? (Y/N)");
scanf("%s", &choice);
}
}

最佳答案

您不能执行 scanf("%s", &choice):&choice“缓冲区”中没有足够的空间来保存您扫描的字符串 - 扫描的字符串位于至少 2 个字符,以 '\0' 结尾,堆栈中的其他变量被覆盖。

改用 scanf("%c", &choice)

关于c -++i 在 while 循环中只改变一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19404146/

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