Here simple code I am not getting the expected output.
#include<stdio.h>
int main()
{
char buf[1024];
while(1)
{
fgets(buf,strlen(buf),stdin);
printf("%s",buf);
printf("hello");
}
}
In the above code I am want whatever the string I enter from keyboard to be printed out to me the same and then hello. As I know fgets() is a blocking function till I input a string from keyboard and press ENTER it will block the program till that time. So when I run it I expect it as follows
$ ./a.out
I input some text here <ENTER>
I input some text here
hello
But actually what I am getting output is infinite loop of "hello" printed on terminal. Why my fgets() not blocking the program? Any idea?
The problem is strlen(buf) is return 0 because buf[0] just happened to be 0 (not guaranteed). You should use sizeof(buf) instead:
fgets(buf,sizeof(buf),stdin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With