gpt4 book ai didi

c - 仅 C 语言中的输入验证 整数

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

我的程序是马里奥金字塔。我似乎无法获得 C 中的输入验证。如果有人可以解释输入验证以及似乎出了什么问题。谢谢。这是我的代码的副本。

// Prompt user till input is 0-23
do
{
printf("Welcome to Mario Pyramid Builder! Enter a number from 0 - 23: ");
scanf("%d", &height);
if(height >= 0 && height <= 23)
{
break;
}
else
{
printf("Wrong Input! Try Again.");
continue;
}
}
while ((height < 0) || (height > 23));

最佳答案

scanf 不会删除多余的字符,它只会提取您放入格式说明符中的内容,其他字符(如\n)保留在缓冲区中。为了避免 scanf 复杂化,请使用 fgets 从键盘读取一行,然后使用 sscanf() 提取整数(或只是简单的旧式atoi())

...
char buffer[128];
if (fgets( buffer, sizeof(buffer), stdin) != NULL)
{
if (sscanf(buffer, "%d", &height) == 1)
{
if (height >= 0 && height <= 23)
{
...
}
else
{
fprintf(stderr, "Height outside valid range [0,23]\n");
}
}
else
{
fprintf(stderr, "Please enter a numeric Height in range [0,23]\n");
}
}
...

关于c - 仅 C 语言中的输入验证 整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49592103/

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