c Language stack string backwards output question

Asked 2 years ago, Updated 2 years ago, 96 views

#include  < stdio.h>
#include  < stdlib.h>
#include  < string.h>

typedef char element;   

typedef struct stackNode { 
    element data;
    struct stackNode *link;
  }stackNode;

stackNode* top;   

void push(element item)    
{
    stackNode* temp=(stackNode *)malloc(sizeof(stackNode));

temp->data = item;
    temp->link = top;
    top = temp;
}

  element pop()   
{
    element item;
    stackNode* temp=top;

    if(top == NULL) {    
        printf("\n\n Stack is empty !\n");
       return 0;
    }

    else{                    
       item = temp->data;
       top = temp->link;
       free(temp);
       return item;
    }
}

void del()     
{
    stackNode* temp;
    if(top == NULL) {    
       printf("\n\n Stack is empty !\n");
    }

    else {                 
       temp = top;
       top = top->link;
       free(temp);
    }
}

  void printStack()       

 {
        stackNode* p=top;
    printf("\n STACK [ ");
    while(p){
       printf("%c ",p->data);
       p = p->link;
    }
    printf("] ");
  }

int main(void)
  {

    element item[50];
    int i=0;
    top = NULL;

    printf ("Enter string: ");

    Do
    {
        scanf("%c",&item[i]);
        push(item[i]);
        i++;
        printStack();
    }while(item[i] != '\n');

    printf("end");
  }

Code that enters a string, puts it in the stack, and outputs it backwards. If you press the string and press enter, the do-while syntax ends and the print end must appear, but the enter value is entered. Change scanf to getchar and it reacts the same way.

For example, if you press enter after entering hello, the enter value is entered as shown in the picture, and the end does not come out I don't know what to do. Help me!

stack enter-key c

2022-09-22 20:31

1 Answers

You will always see a value that is empty because of increasing the index (i++) before checking the character to exit while. If you change it like below, it will work well.

int main(void)
  {

    element item[50];
    int i=0;
    top = NULL;

    printf ("Enter string: ");

    Do
    {
        scanf("%c",&item[i]);
        push(item[i]);
        i++;
        printStack();
      } while(item[i - 1]!= '\n'); // Changed
    printf("end");
  }


2022-09-22 20:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.