float应该只接受正确的输入

时间:2017-10-22 09:06:47

标签: 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.

如您所见 4.fuu 不是有效输入,因此应显示[ERR]消息! 我的功能如下:

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;
}

我很感激任何帮助,链接,参考和提示!

1 个答案:

答案 0 :(得分:3)

非常感谢 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;
}