how can i control float input in c?

scanf returns the number of inputs successfully converted and assigned, so as a first step you need to check the return value:

if ( scanf( "%f %f", &x1, &y1 ) != 2 )
{
  // handle bad input
}
else
{
  // process x1 and y1
}

If you enter something like "1.0 2.0", scanf will successfully convert both values and assign them to x1 and y1 and return 2. If you enter something like "1.0 abc", scanf will convert and assign 1.0 to x1, stop reading as soon as it sees "abc" (and not update y1), and return 1. And if you enter "abcdef", nothing gets assigned to either x1 or y1 and scanf returns 0.

If you enter something like "1.0 2abc", scanf will read and convert the "1.0" and set x1 to 1.0 as expected. It will also read and convert the "2" from "2abc" and set y1 to 2.0, and scanf will return 2. This is not a good situation – you would probably want to reject that "2abc" altogether, but scanf with %f by itself can’t do that.

The problem you have to deal with now is that those characters that weren’t converted are still in the input stream – until you remove them with some other input operation, they will prevent any further floating-point inputs from being recognized. So as part of handling bad input, you need to clear out the input stream. We’ll rewrite our check as follows:

/**
 * Repeat input operation until we get two good inputs:
 */
while ( scanf( "%f %f", &x1, &y1 ) != 2 )
{
  /**
   * First make sure there isn't a problem with the input stream itself;
   * if there is, exit the program at this point.
   */
  if ( feof( stdin ) || ferror( stdin ) )
  {
    fprintf( stderr, "Error or EOF on stdin, exiting...\n" );
    return EXIT_FAILURE;
  }

  /**
   * Bad input, read and discard everything up to the next newline
   */
  while ( getchar() != '\n' )
    ; // empty loop

  printf( "Bad input, try again: " );
}
// process x1 and y1

By itself, scanf really isn’t a good tool for validating input, but this should get you going. Just be aware that the solution above won’t catch the "1.0 2abc" case, but I don’t think you want to get into those weeds right now.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top