gpt4 book ai didi

C - Do While 循环中的无限循环

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

我需要循环一个循环直到它结束,但是即使 i>=k 编译器也会继续循环,并且我无法退出无限循环。这段代码有什么问题?

int i=0;
User signed_up[k]
char input_user[15];
bool stop_cycle=false;

do {
printf("\n\n%*sUsername: ", 26, "");
fflush(stdin);
scanf("%s", input_user);
stop_cycle=true;

for (i=0;i<k;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
printf("\n%*sUsername inserito gi%c presente nel database!", 26, "", 133);
}
stop_cycle=false;
}
} while (!stop_cycle);

编辑:k 是一个计数器,每次运行时都会在子例程注册中增加。此时代码可能是 0、1 等。我想要实现的是每次插入已经存在的用户名时询问再次插入它,直到数组中的搜索结束。

最佳答案

您到底想在这里做什么?

您的代码执行的步骤既在每次 do 迭代中将 i 变量重置为 0,又在每次迭代中将 stop_cycle 设置为 true 和 false。

每次 do 迭代的 for 循环从 i=0 运行到 i < k。

您可以通过每次将停止周期设置为 false 来结束 do,因此 while 永远不会触发。

尝试运行它:

printf("\n\n%*sUsername: ", 26, "");
fflush(stdin);
scanf("%s", input_user);

for (i=0;i<k;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
printf("\n%*sUsername inserito gi%c presente nel database!", 26, "", 133);
}
}

int i=0;
User signed_up[k]
char input_user[15];
bool stop_cycle=true;

do {
printf("\n\n%*sUsername: ", 26, "");
fflush(stdin);
scanf("%s", input_user);
stop_cycle=true;

for (i=0;i<k;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
printf("\n%*sUsername inserito gi%c presente nel database!", 26, "", 133);
stop_cycle=false;
}
}
} while (stop_cycle);

注意第二个版本中停止循环变量的位置及其值的变化。

关于C - Do While 循环中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432569/

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