0

I was making a program to enter numbers into a stack and the do-while loop was automatically finished without waiting for my response. Hence only one data was taken and displayed.

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

struct node
{
    int data;
    struct node *next;
};
typedef struct node NODE;

NODE *top = NULL;

void push(int x)
{
    NODE *p;

    p = (NODE*)malloc(sizeof(NODE));
    p->data = x;
    p->next = top;
    top = p;
}

void display(void)
{
    NODE *t;

    t = top;
    if(t == NULL)
    {
        printf("\nstack is empty");
    }
    else
    {
        while(t != NULL)
        {
            printf("%d ", t->data);
            t = t->next;
        }
    }
}

int main(void)
{
    int m;
    char ans;

    do
    {
        printf("\nEnter the no. to insert in stack: \n");
        scanf("%d", &m);
        push(m);

        printf("\nDo you want to enter more data???\n");
        scanf("%c", &ans);
    } while(ans == 'y' || ans == 'Y'); // here after entering a value for variable 'm', the program terminates displaying the stack with one element.

    display();
    return 0;
}
fluter
  • 13,238
  • 8
  • 62
  • 100
Sudeep
  • 45
  • 6

2 Answers2

4

Please change

scanf("%c", &ans);

to

scanf(" %c", &ans);

Notice the added space, which consumes the newline which was left in the input buffer after the previous input.

Note that some format specifiers such as %d and %s automatically consume any leading whitespace, and leave in the buffer the next character which does not suit the format. In the case of your %d that was a newline.

The format %c however, collects the next character from the input buffer no matter what it is, and the leading space prevents that.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

Besides the adding of the space in format string to consume the newline mentioned above, it's also a good practice to check scanf return value, as it might be failed to input an integer value and still push the old value of m onto the stack.

int main(void)
{
    int m;
    char ans;
    int ret;
    do
    {
        printf("\nEnter the no. to insert in stack: \n");
        ret = scanf("%d", &m);
        if (ret != 1) {
            printf("invalid input\n");
            continue;
        }
        push(m);

        printf("\nDo you want to enter more data???\n");
        ret = scanf(" %c", &ans);
        if (ret != 1) {
            printf("invalid input\n");
            continue;
        }
    } while(ans == 'y' || ans == 'Y');
}
fluter
  • 13,238
  • 8
  • 62
  • 100