0

I am making a program about stack, but everytime I enter a case choice, it loops the number i entered. Why so?

example : Enter your choice: 1 1 1 1 1 1 1 1 1 1- it doesnt stop asking

void display();
void push();
void pop();
void stackList();
int stack[100];
int top = -1;

int main(){

char ch;
char character; *// user input of char*

    display ();

    printf("\n\nEnter your choice: ");

    do 
    {   
        scanf("%c",&ch); *// enter choice of user* 

         switch(ch)
         {
            case 1: push();      break;
            case 2: pop();       break;
            case 3: stackList(); break; *// display stacks*
         }
     
     }
     while( ch != 'z' || ch != 'Z');
 
  }

this is my push function

 void push ()
    {

    char character;

    printf("\n\npress 'Z' to exit.......");

    if ( top == MAX -1 )
    {
        printf(" OVERFLOW ");
    }

    else
    {
        printf("Enter a character to push:\n");   
        do 
        {   
            scanf("%c",&character); *// asking user for character*
        
            top = top+1;
            stack[top]=character;
        }
     
    while( character != 'z' || character != 'Z');
    printf("\nExiting...");
    
    }   
}

** for example : Enter your choice: 1 1 1 1 1 1 1 1 1 1- it doesnt stop asking **

xxx
  • 35
  • 5
  • 1
    `scanf(" %c",&ch);` – Sourav Ghosh Dec 17 '20 at 10:31
  • 1
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Change `scanf("%c",&ch);` to `scanf(" %c",&ch);` and other use cases - note the added space before `%`. Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Dec 17 '20 at 10:32
  • 2
    Also please change `case 1:` etc to `case '1':` etc. – Weather Vane Dec 17 '20 at 10:34
  • @WeatherVane oh i thank you i didn't notice – xxx Dec 17 '20 at 10:35
  • 1
    Or, change `ch` to be an integer. – Sourav Ghosh Dec 17 '20 at 10:40
  • @SouravGhosh yes i changed it, i got confuse by my variables – xxx Dec 17 '20 at 10:59

0 Answers0