gpt4 book ai didi

c - 在 do-while 的第二个循环中显示错误消息

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

如果我有一段时间或在 C 中执行 while 循环,是否有某种( native )方法可以在第二个循环中发生某些事情?

我要求获得输入;我有这个:

int size;
do {
printf("Size of tower (0 <= x <= 23): ");
scanf("%i", &size);
} while (size > 23 || size < 0);

如果用户输入的值不在 0 到 23 之间,我想显示一条错误消息并要求输入另一个值。显然我可以这样做:

int size;
int error = 0;
do {
if (error) { printf("Invalid size\n"); }
printf("Size of tower (0 <= x <= 23): ");
scanf("%i", &size);
error = 1;
} while (size > 23 || size < 0);

但是,这感觉很恶心。我正在寻找一个优雅的解决方案,我认为在第二个循环上运行一些东西会起作用。

最佳答案

我想你想要这样的东西:

int size = -1;
int MAX_TRIES = 10;
while (MAX_TRIES--)
{
printf("Size of tower (0 <= x < 23): ");
if (scanf("%i", &size) != 1)
{
printf("Read error!!\n");
break;
}

if (size >= 0 && size < 23)
{
break;
}

printf("Error: You entered '%d' which is not in the range 0 <= x < 23\n", size);
}

通过这种方式编写,您不必在编写代码时在脑子里计算 bool 条件逻辑的否定。
此外,检查 scanf() 的返回值也很重要。感谢 Weather Vane's comment提醒这一点。
此外,最好限制此循环的执行次数,而不是让它运行到无穷大。 (感谢 Jonathan Leffler's comment)

关于c - 在 do-while 的第二个循环中显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646383/

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