fgets() reads characters until the size of the buffer is reached, a '\n', or EOF or some other error (as you have discovered ).
Code:
char buf[80];
int len;
fgets(buf,sizeof(buf),stdin);
len = strlen(buf)-1;
if( buf[len] == '\n')
buf[len] = 0;
->
Code:
char buf[80];
size_t len;
fgets(buf,sizeof(buf),stdin);
len = strlen(buf)-1;
if( buf[len] == '\n')
buf[len] = 0;
strlen() returns a size_t, not an int. Your compiler shold catch this if you enable warnings.
Dave_Sinkula, in reference to your link, does fflush(stdout) clear errors from a stream? Because if it doesn't, you'll need a clearerr() in there too.
Salem's point was not that any user might input a pointer. The point was if you ( at some time ) put your code into a function ( as in my example ) the array degenerates to a pointer and then the code
Code:
if(strlen(buffer)==(sizeof(buffer)-1)) buffer[strlen(buffer)-1]='\0';
breaks
That's because sizeof returns the size of the variable in memory. For a char array, it returns the number of characters in the array, because that's how much memory the array takes up. But for a pointer, it will return 4 (on 32 bit machines) or 2 (on 16 bit machines) or maybe 8 (for 64 bit ones).
Another thing wrong with that code is that calling strlen twice invokes a lot of unnessesary overhead. You can save the value (remember to use a size_t!), as AD did.