c - float 应该只接受正确的输入

标签 c function validation

我写了一个 get_float() 函数,它应该只接受有效的浮点值,只有正值,并且该值必须大于零且小于 FLT_MAX: (FLT_MAX > length > 0)

除一种情况外,此功能在所有情况下都能发挥作用:

~$ gcc -Wall -std=c11 -o ValidatedFload ValidatedFload.c
~$ ./ValidatedFload 
Please enter a length: asd
[ERR] Invalid length.
Please enter a length: -1
[ERR] Invalid length.
Please enter a length: 0
[ERR] Invalid length.
Please enter a length: 4.fuu
[OK]  Valid length.

As you can see 4.fuu is not a valid input, therefore the [ERR]-message should appear! My function is the following:

float get_float()
{
  const float FLT_MAX = 100.0;  // Max size of a triplet length
  float length = 0;             // Temporary saves the triangle lengths
  char loop = 'y';              // Boolean value for the read-in-loop

  while (loop == 'y') {
    printf("Please enter a length: ");
    scanf("%f", &length);
    if ((length > 0) && (length < FLT_MAX)) {
      printf("[OK]  Valid length.\n");
      loop = 'n';
    }
    else{
      printf("[ERR] Invalid length.\n");

      // Flushes the input buffer, to prevent an endless loop by 
      // wrong input like '5.fuu' or '1.23bar'
      while ((getchar()) != '\n');
    }
  }
  return length;
}

我非常感谢任何帮助、链接、引用和提示!

最佳答案

非常感谢 EdHeal,我能够通过检查 scanf() 返回值来解决问题:

float get_float()
{
  const float FLT_MAX = 100.0;  // Max size of a triplet length
  float length = 0;             // Temporary saves the triangle lengths
  char loop = 'y';              // Boolean value for the read-in-loop
  char term;

  while (loop == 'y') {
    printf("Please enter a length: ");

    if (scanf("%f%c", &length, &term) != 2 || term != '\n') {
      printf("[ERR] Invalid length.\n");
      while ((getchar()) != '\n');  // Flushes the scanf() input buffer
    }
    else {
      if ((length > 0) && (length < FLT_MAX)) {
        printf("[OK]  Valid length.\n");
        loop = 'n';
      }
      else{
        printf("[ERR] Invalid length.\n");
      }
    }
  }
  return length;
}

关于c - float 应该只接受正确的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872334/

相关文章:

javascript - 我怎样才能用另一个函数包装每个快速路由处理程序

javascript - “检查信件”验证无效

php - 验证上传的文件是否为实际图像文件很重要吗?

c - 与 Node 和 Node-gyp 一起使用的 AWS Lambda 上出现奇怪的 "memory"行为

c - 在标准 C 中从头开始实现 memcpy 在技术上是不可能的吗?

c - argv 的双指针

javascript - 表单未验证 - javascript

c - 使用 net-snmp C API 设置值时出现问题

Python 语言问题 : attributes of object() vs Function

postgresql - 使用 DO DECLARE 和 EXECUTE 的 Postgres DROP TABLE