Here's an example below, same problem. I know that it's highly unlikely for a user to type 255 characters or whatever, but just the same, I'd like to have a program where if they do it stops it. My problem is that if the user types more than the size of STRING, then everything works fine when I clear the buffer. but if they DON'T, then when my program gets to the line designed to clear the buffer, the user has to hit enter to provide it with that \n it's waiting for. How can I fix this? Thanks
Code:
#include <stdio.h>
int main() {
int i;
int cb;
char string[BUFSIZ];
fgets(string,sizeof(string),stdin);
for (i = 0; i < sizeof(string); i++) {
if (string[i] == '\n') { string[i] = '\0';}
}
//I had left this part out before, making the '\n' a '\0'
//however, same issue, even setting the size to BUFSIZ, if the user enters
//6 solid lines of garbadge, it's enough to over flow it, and that getchar down
//below grabs the \n like it should not. But if I put in a line to clear the buffer, then
//the user has to hit enter to get past that line if they didn't overflow the string size.
printf("got it");
getchar();
return 0;
} //as this example illustrates, setting the string length only to 2 makes it so that you don't need to
//set up a loop to take the \n and change it to \0 like you normally would with fgets, because in this
//case it doesn't have room to store it, so it stores the 1st letter, then the \0, and tosses the \n in the buffer.
//However, you would then need to clear the buffer, so that the getchar doesn't eat up the \n. But if you do that
//then if the user just hits ENTER at the fgets, he has to hit enter 2 more times, because the while((cb=getchar))
//eats up the second \n. So it's better to just always have the string value be at least 3(for where you only need
//1 single digit value), so there's room for the value, the \n, and the \0. Of course, then you'd still probably
//need to clear the buffer at some point. And if they didn't type more than what fgets read, then clearing the
//buffer will force the user to hit ENTER to continue when you do it, but if they did, it will eat up the extra
//characters like it should.