0
do
{
    printf("1 :Enter Company Deatils\n");
    printf("2 :Display stoke Deatils\n");
    printf("0 :Exit\n");
    printf("\nEnter num: ");
    scanf("%d", &n);
    switch (n)
    {
        case 1:
            enter();
            break;
        case 2:
            display();
            break;
    }
}
while (n != 0);

When I enter 2 to call display function after that scanf() not taking any input and running loop for infinite time.

void display_d(){
    point c1;
    FILE *fptr;
    fptr = fopen("company_det.txt","r");
    while(fread(&c1,sizeof(point),1,fptr)){
        printf("\n%s %s %d\n",c1.company_name,c1.bla.date,c1.bla.price);
    }
    fclose(stdin);
}

this is my display function

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    `fflush(stdin);` leads to undefined behavior. See https://stackoverflow.com/questions/2979209/using-fflushstdin – Yun Sep 03 '21 at 10:22
  • This looks like C. Is the c++ tag relevant? – Yun Sep 03 '21 at 10:26
  • @yun after removing fflush(stdin); still having same problem – tapesh menaria Sep 03 '21 at 10:30
  • Then the `display()` function must contain an infinite loop? The code looks fine otherwise. – Yun Sep 03 '21 at 10:34
  • void display() { point c1; FILE *fptr; fptr = fopen("company_det.txt", "r"); while (fread(&c1, sizeof(point), 1, fptr)) { printf("\n%s %s %d\n", c1.company_name, c1.bla.date, c1.bla.price); } fclose(stdin);} ///my display functin – tapesh menaria Sep 03 '21 at 10:46
  • Could you please edit your question to include this function? – Yun Sep 03 '21 at 10:47
  • Please [edit] your question to provide more info and a [mre]. Down here in the comments it gets bent and lost. – Yunnosch Sep 03 '21 at 10:47
  • `fclose(stdin)` causes any attempt at reading from `stdin`, such as by `scanf` later, to invoke undefined behavior. – Yun Sep 03 '21 at 10:49
  • Please replace both function calls by simple prints to narrow down the location of the problrm. What happens? – Yunnosch Sep 03 '21 at 10:50
  • you can check display() function i have just edited the code – tapesh menaria Sep 03 '21 at 11:13

1 Answers1

2

The function display_d() closes stdin. When the function returns, scanf will try to use stdin to read another digit. This is undefined behavior (see answers here).

You probably meant to close the file instead of stdin.

Also, the return value of fopen should be checked. It will be NULL if fopen failed to open the file.

Yun
  • 3,056
  • 6
  • 9
  • 28