PatrickSteiner
PatrickSteiner

Reputation: 527

float should only accept correct inputs

I wrote a get_float() function which should only accept valid float-values, only positive values and the value must be greater zero and less FLT_MAX: (FLT_MAX > length > 0).

This functions does its purpose in all but one case:

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

I am grateful for any help, links, references and hints!

Upvotes: 1

Views: 139

Answers (1)

PatrickSteiner
PatrickSteiner

Reputation: 527

Great thanks to EdHeal, I was able to fix the problem by checking the scanf() return value:

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

Upvotes: 3

Related Questions