gpt4 book ai didi

c - C编程中如何用异常过滤掉字符

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:35 26 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序,要求用户输入,如果输入介于给定的 float 之间,则会出现输出。在这种情况下,如果输入速度为 20.5,则输出将是您处于二档。我想过滤掉所有无效输入。

我已经有了某种过滤器,但效果不佳。如果输入是“afgegq”,它将被过滤并再次询问我输入。但是如果是156FFAGFAE。它不会被过滤。

#include <stdio.h>
#include <stdlib.h>

int main()
{
for (;;)
{
int versnelling[5] = {1, 2, 3, 4, 5};

float speed = 0;
printf("Please enter a speed: ");
if (scanf("%f", &speed) != 1)
{
fputs("error: invalid input. Please enter a number\n",stderr);
return 0;
}

if (0.0 < speed && speed < 10.0)
{
printf("The gear you are in is: %i\n", versnelling[0]);
}
else if (speed >= 10.0 && speed < 30.0)
{
printf("The gear you are in is: %i\n", versnelling[1]);
}
else if (speed >= 30.0 && speed < 60.0)
{
printf("The gear you are in is: %i\n", versnelling[2]);
}
else if (speed >= 60.0 && speed < 80.0)
{
printf("The gear you are in is: %i\n", versnelling[3]);
}
else if (speed >= 80.0 && speed <= 100)
{
printf("The gear you are in is: %i\n", versnelling[4]);
}
else if (speed > 100)
{
printf("I can not go faster then 100km/h \n");
}
else if (speed == 0)
{
printf("The gear you are in is: Neutral\n");
}
else if (speed < 0 && speed > -15)
{
printf("The gear you are in is: R\n");
}
else if (speed < -15)
{
printf("I can not go that fast in reverse\n");
}
}
}

我希望它过滤掉除数字和字母 Q 之外的所有内容。我需要字母 Q,因为我想创建输入的平均值(稍后我将尝试找出方法)。但要知道我需要这个。提前谢谢你。

最佳答案

处理错误用户输入的最佳方法是首先读取,然后使用strtof() 将其解析为float

    printf("Please enter a speed: ");
fflush(stdout); // Insure prompt is printed first

char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) {
printf("End of file\n");
return 0;
}

if (toupper((unsigned char) *buf) == 'Q') == NULL) {
printf("Q detected\n");
break;
}

char *endptr; // location to store end of parsing
errno = 0;
*f = strtof(buf, &endptr);
bool no_conversion = buf == endptr;

// Allow trailing white-space
while (isspace((unsigned char) *endptr)) {
endptr++;
}

if (no_conversion || *endptr) {
fputs("error: invalid input. Please enter a number\n", stderr);
continue; // No conversion or junk at the end
}

// Add additional tests if one wants to detect out-of-range (not shown)

....

关于c - C编程中如何用异常过滤掉字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58075595/

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