In my C program, fgets
is not reading any data. Please see the below code:
#include <stdio.h>
int main()
{
char string[50];
int marks,i,n, limit;
printf("Enter Limit : \n");
scanf("%d", &limit);
FILE *fptr; fptr=(fopen("string.txt","w"));
if(fptr==NULL){
printf("Error!");
return 0;
}
printf("Enter a string : \n");
fgets(string, sizeof(string), stdin);
fwrite(string, 1, sizeof(string), fptr);
fclose(fptr);
return 0;
}
After I entering limit, the program shows "Enter a string" and just exits(Before entering any data). If I remove the scanf("%d", &limit);
statement it works fine. Also if add a getchar();
statement above fgets
it will work fine. Does anyone know the reason behind this issue?