I am trying to make a safe input function, since it's tedious to keep writing a bunch of crap with fgets() every time you want to get some input from the user safely.
This is what I have written so far, and I know it's far from perfect:
First off, I know that if nothing is left in the input buffer because the destination string and the input received are both the same size, then the scanf function is an error.Code:#include <stdio.h> #include <string.h> void gstring /*Sexy*/ (char *destination_string) { char *p; if ( (fgets(destination_string, sizeof(destination_string), stdin)) != NULL ) { if ( ((p = strrchr(destination_string, '\n')) != NULL) ) *p = '\0'; else /*ungetc('x', stdin); One idea, to always make the scanf call have a purpose*/ scanf("%*s"); } else puts("Error encountered reading string."); return; }
How would I go about checking the input buffer?
The other solution I have is to make a string in the function, of say BUFSIZ, which should be large enough to accommodate any string input, and then strncpy() the appropriate length to the destination string.
Another idea I was thinking of, was using ungetc() to force something onto the input buffer, so that the call to scanf to clear the input buffer would always have a purpose.
If someone could look this over and give any ideas/tips, I'd be thankful.
Thanks.