Good day...
In order to analyze how the fgets function works, I wrote this little program:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char line[10];
fgets(line, sizeof(line), stdin);
printf("%sworld", line);
getchar();
return 0;
}
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.
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
Code:
void get_rid_of_newline(char line[])
{
int c;
char *ptr;
if((ptr = strchr(line, '\n')) != NULL)
*ptr = '\0';
else
while((c = getchar()) != '\n' && c != EOF)
;
}
and use right after each user input. What do you have to say about all of this? Thanks for your comments and suggestions.