i dont normally work in the console/terminal window in my day job. so, i keep rewriting this every time i respond to someone needing help related to getting user input. im putting it here partly so i dont have to keep rewriting it.
this function will get a string input safely from the user and flush any extra characters if they enter too many.
if you (the programmer) need to get an integer or double floating point value from your program's user, then just follow up this code with a call to the strtol() or strtod() function from the standard C library, <stdlib.c>
this function forces the user who inputs the string to stay within boundaries, but just as importantly, it does not tempt the programmer (you) to use dangerous functions that could overflow buffers or get input "trapped", or to use undefined functions to try and flush the input buffer, etc.
And if your user does not input the correctly formatted value(s) that your program is looking for, strtol, strtod, etc. will point that out and allow you to handled invalid input gracefully.
Edited 6 Years Ago by jephthah: n/a