I'm trying to use fgets
to read from stdin
, but in small blocks. My issue is that I'm not sure what fgets
equals when at the end of stdin. From my code, it seems that it clearly isn't NULL
or another end of line like \n
. What is the proper way to do this?
Code (which loops forever since fgets
never equals NULL
):
int main ()
{
char str1[4];
printf("Enter stuff: ");
while (fgets(str1, sizeof str1, stdin) != NULL &&
fgets(str1, sizeof str1, stdin) != "\n") {
printf("Got here");
}
printf("%s\n",str1);
return 0;
}
Change
while(fgets(str1, sizeof str1, stdin) != NULL && fgets(str1, sizeof str1, stdin) != '\n'){
to
while(fgets(str1, sizeof str1, stdin) != NULL){
or to
while(fgets(str1, sizeof str1, stdin)){
fgets
returns a char*
. You can't compare it to '\n'
which is a char
. This function, returns NULL
when it encounters EOF
. You can simulate EOF
on stdin
by pressing