So is there any way of rejecting \n from being entered as a field?
... to make it more robust and foolproof.
Code should not prevent '\n'
from being read via fgets()
. Instead, code should assess that input for validity. A leading '\n'
is likely only 1 concern. Make code easy to update as certainly the criteria for a valid name will evolve.
I recommend a separate name test.
bool ValidNameInputTest(const char *userinput) {
if (*userinput == '\n') return false; // fail
// add other tests as needed
return true;
}
In a loop, test and repeat as needed. Code should exit the loop on success. When an end-of-file or input error occurs, code should detect/handle that too.
...
char userinput[50];
do {
printf("Enter Name : ");
fflush(stdout); // add to insure above output is seen before reading input
//memset(userinput, '\0', 50);// Commented out as not needed - although useful for debug
// Check return value and used a derived size
//fgets(userinput, 50, stdin);
if (fgets(userinput, sizeof userinput, stdin) == NULL) {
Handle_EndOfFile_or_Error();
}
} while (!ValidNameInputTest(userinput));