0

I am getting an infinite loop in trying to input data using switch statement inside while loop....Here is the code part :

do{
   printf("Enter option:\n 1.push\n 2.pop\n 3.Size of Stack\n 
           4.TopElement\n");

  scanf("%d ",&p);

  switch(p){
    case 1:
            while(ch!='n'){
              printf("Enter data\n");
              scanf("%d",&x);
              push(x);
              printf("\nWant to enter more data? y or n ?\n");
              scanf(" %c",&ch);//ch=getchar();
             }
    break;

    case 2: while(ch!='n'){
      pop();
      printf("Wanna pop more ? Enter y or n\n");
      scanf(" %c",&ch);//ch=getchar();
    }
    break;

    case 3:
    Stacksize();
    break;

    case 4: TopElement();
    break;

    default: exit(0);
}
printf("Wanna continue ? Enter choice y or n\n");
scanf(" %c",&choice);

}while(choice!='n');

When I enter '1' then it is going in infinite loop. I suppose control should go to switch and print "Enter data" but this is not happening..

ch and choice are of type char

Aditya kumar
  • 76
  • 1
  • 11
  • 2
    No; when you enter `1`, the `scanf("%d ",&p);` is not returning because of the trailing blank. You should be checking the return value. You should add a print after it saying "Hi, I'm here"; you wonb't see that. You have to enter something other than white space (not a newline, blank, tab) to get that `scanf()` to return. I hope you guessed right about what the next input needs to be. – Jonathan Leffler Nov 29 '17 at 07:17
  • 1
    Obligatory: always check return vale of scanf – hyde Nov 29 '17 at 07:19
  • Please never include trailing whitespace in `scanf()` format strings; this is almost always a mistake. – ad absurdum Nov 29 '17 at 07:34

0 Answers0