I'm writing a client/server program as part of an operating systems class. I didn't realize how horrible I/O is in C until I started writing this program. I'm NOT using scanf() for obvious reasons, but fgets() is still giving me some trouble.
Basically, I'm reading in 2 values with fgets() and I'm removing the \n character and replacing it with \0. But the problem is that if I write more input than fgets() is looking for, then I have a bunch of garbage still in the stdin buffer that ends up writing itself into my second variable. Here is (some of) my code:
Only MAX_ISBN number of characters are being read into the string to prevent buffer overflow, but if I type more characters than MAX_ISBN it automatically inputs those extra characters into the next variable that is being input. The problem is easily solved using the following line of code:
printf("\n %s","Enter the ISBN Number of the Book: ");
if (isbnNo[i] == '\n')
isbnNo[i] = '\0';
printf("\n %s", "Enter the Book Title: ");
if (bookTitle[i] == '\n')
bookTitle[i] = '\0';
However, if I didn't type more characters than MAX_ISBN then this will pause the system and wait for an extra newline character.
while(getchar() != '\n') continue;
Basically, I need a way to check if stdin needs to be flushed using the above line. Is there anyway to check if there is anything on the buffer (like a peek() function)? I tried using fflush(stdin) instead of the above line of code, but it doesn't work. Can anyone help?