c - C 中的数据验证 - 确保输入格式正确

标签 c validation

我想写一段代码来确保用户只输入一位数字。如果用户输入类似“0 1 3”的内容,我希望我的程序读取错误消息,但我不知道该怎么做。任何人都知道如何处理这个问题?如果用户输入中间有空格的一堆数字,我当前的代码只接受第一个数字。

请看下面我的代码。谢谢:D

//Prompt the user to enter the low radius with data validation
printf("Enter the low radius [0.0..40.0]: ");
do
{   
    ret = scanf("%lf", &lowRadius);
    //type validation
    if (ret != 1)
    {
        int ch = 0;
        while (((ch = getchar()) != EOF) && (ch != '\n'));
        printf("Wrong input. Please enter one numerical value: ");  
    }
    //range validation      
    else if((lowRadius < 0 || lowRadius > 40))
    {
        printf("Incorrect value. Please enter in range 0-40: ");
    }
    else break;
} while ((ret != 1) || (lowRadius < 0 || lowRadius > 40));//end while lowRadius

最佳答案

如果将该行读入一个字符串,然后对其进行分析,就可以避免因未提供的输入而挂起的问题。您已经完成了大部分工作,但这显示了如何捕获过多的输入。它的工作原理是扫描 double 之后的字符串以获取更多输入。 sscanf 的返回值告诉您是否存在,因为它返回成功扫描的项目数。

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

void err(char *message)
{
    puts(message);
    exit(1);
}

int main(void)
{
    double lowRadius = 0.0;
    char inp[100];
    char more[2];
    int conv;
    if(fgets(inp, sizeof inp, stdin) == NULL) {
        err("Input unsuccesful");
    }
    conv = sscanf(inp, "%lf %1s", &lowRadius, more);  // conv is number of items scanned
    if(conv != 1) {
        err("One input value is required");
    }
    if(lowRadius < 0.0 || lowRadius > 40.0) {
        err("Number out of range");
    }
    printf("%f\n", lowRadius);
    return 0;
}

我不确定您对个位数的规定,因为这不允许输入最大值。

关于c - C 中的数据验证 - 确保输入格式正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37242890/

相关文章:

c - 文件范围变量和 C 中的函数参数的名称可能相同。可以区分吗?

c - 是否可以通过修改 inode 数据结构和 super block 来连接同一 linux 文件系统上的两个文件?

java - 车牌号验证程序JAVA

ios - Swift - 如何将 SwiftValidator 集成到我的项目中

c++ - 输入验证难题

java - 为什么 validator 没有被调用?

python - 在 FormAlchemy 中不需要非 NULL 字段(允许空字符串)

c - 带有#include 指令的尾随字符

c - 如何从 C 中的二维数组中读取多个文件

c - 如何针对内存使用优化 GCC 编译?