I'm a student in software engineering and I'm on Christmas break in order to get better for the next semester I've been writing various console applications to practice. I have however ran into a problem, I need to get integer input from the user. I've been using fgets
to get the string from stdin
and then using sscanf
to get the integer (Which has worked fine) but if the user enters more than my buffer size trailing characters are left in the stream (Including a newline with skips my next call to fgets
). I've looked around and found that most people seem to suggest while(getchar() != '\n');
that however causes me a problem because if there isn't a newline character to be consumed an unnecessary scan for input takes place.
Example:
int ch;
char* buffer = (char*)malloc(BUFSIZ*sizeof(char));
while((ch = getchar()) != '\n' && ch != EOF);
fgets(buffer,BUFSIZ*sizeof(char),stdin);
If the buffer isn't too small and no trailing characters remain in the stream then there is an unecessary getchar()
causing input.
Output:
A
A
You typed A
Intended Output:
A
You typed A
I hope that I made this clear enough, I appreciate any help.