It should be noted that it might still be necessary to flush the input when using "fgets()" with stdin.
Consider these two examples:
Code:
/* example 1 - User input less than array size - newline gets stored */
char userString[10];
fgets(userString,10,stdin);
/* user enters "Hello\n" */
userString[0] = 'H'
userString[1] = 'e'
userString[2] = 'l'
userString[3] = 'l'
userString[4] = 'o'
userString[5] = '\n'
userString[6] = '\0'
/* it's usually desired to have additional code that removes the newline from the array */
Code:
/* example 2 - User input greater than array size */
/* Protected from overflow, but newline does not get stored */
char userString[5];
fgets(userString,5,stdin);
/* user enters "Goodbye\n" */
userString[0] = 'G'
userString[1] = 'o'
userString[2] = 'o'
userString[3] = 'd'
userString[4] = '\0'
/* no newline in array - this means 'b', 'y', 'e', and '\n' are still */
/* waiting on the buffer and need to be removed */
I usually approach user input like this:
- Read from stdin with "fgets()"
- If there's a newline in the string, replace it with a null character
- Else, flush the input buffer (such as with the example provided in the link by vart in post #2)
- Process/validate data
- etc...
It's obviously best to have this sort of code in its own function. As an exercise, you can create separate functions for reading strings, reading integers, etc, using the advice given by grumpy and anduril462.