Make sure the user enters a valid floating-point number in C I would like to know if this is a good way to make sure the user enters a valid number.

#include &lt;stdio.h&gt;
#include &lt;ctype.h&gt;

void clear_stream(FILE *in)
{
   int ch;
   clearerr(in);

   do
      ch = getc(in);
   while (ch != '\n' &amp;&amp; ch != EOF);

   clearerr(in);
}

float retreive_input()
{
    float input = 0;
    fflush(stdout);
    while (scanf_s("%f", &amp;input) != 1)
    {
        clear_stream(stdin);
        printf("Invalid number. Please try again: ");
        fflush(stdout);
    }

    return input;
}

int main()
{
    float input = 0;
    printf("ENTER A NUMBER: ");
    input = retreive_input();
    printf("YOUR INPUT: %f", input);

    getchar();
    return 0;
}
@Justin advice is solid.  Read a line.


scanf_s("%f", &amp;input) offers no advantage over the more portable scanf("%f", &amp;input)
scanf_s/scanf("%f", &amp;input) allows the user to enter multiple lines before the number - so a blank line of input is not detected.
scanf_s/scanf("%f", &amp;input) does not detect trailing non-numeric input.
while (scanf_s("%f", &amp;input) != 1) does not cope with non-numeric entries - they remain in stdin.
Overflow is UB with scanf() and friends.


Instead separate the task: input, parsing.

#define MAXLINE_SIZE 100
char buf[MAXLINE_SIZE];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF();

size_t len = strlen(buf);
if (len == 0 || buf[len-1] != '\n') {
  // consider the line hostile and fail it.
  // consume rest of line
  clear_stream(stdin);
  return FAIL;
}


Parse using strtod() - Simple example.  Additional considerations if over/underflow detection needed.

errno = 0;
char *endptr;
float y = (float) strtod(buf, &amp;endptr);

if (buf == endptr) Handle_NoConversion();
// consume trailing spaces
while (isspace((unsigned char) *endptr) endptr++;
if (*endptr) Handle_TrailingJunk(). 

// Good to go;
return y;


Good use of fflush(stdout); before input and after the re-prompt that may lack a \n.  I would not hard code in the re-prompt value, but pass it in.

Good use of int ch; when testing the return value of getc().

Using %f to print floating point is problematic should the float be small (output only 0.000000) or large (many to hundreds of digits).  Consider %.*e