In order to analyze how the fgets function works, I wrote this little program:
This is how I understand this: if I type something with eight characters and hit enter, fgets will read the eight characters plus the \n and put a \0 at the end. Am I correct? The getchar() function forces me to hit enter again to exit the program because there's nothing in the input buffer.
fgets(line, sizeof(line), stdin);
Now if I type something with nine characters, will fgets read the nine characters, put a \0 at the end of the array and put leave the \n in the input buffer? Am I correct here?
I am wondering now what would be a good way to take care of this in a, let's say, menu loop.
I was thinking about creating a function something along the following lines
and use right after each user input. What do you have to say about all of this? Thanks for your comments and suggestions.
void get_rid_of_newline(char line)
if((ptr = strchr(line, '\n')) != NULL)
*ptr = '\0';
while((c = getchar()) != '\n' && c != EOF)