When the door turns weird, scanf

Asked 1 years ago, Updated 1 years ago, 123 views

#include <stdio.h>
#include <stdlib.h>
#defineMAX_STACK_SIZE 100 // Declare Global Variables
char stack[MAX_STACK_SIZE];
int top = -1;        
void stackFull() {
    fprintf(stderr, "Stack is full, cannot add element");
    exit(1);
}
void stackEmpty() {
    fprintf(stderr, "Stack is Empty");
    exit(1);
}
void push(char a)
{
    if (top >= MAX_STACK_SIZE - 1)
        stackFull();
        stack[++top] = a;  
}
char pop(char a)
{
    if (top == -1)
        stackEmpty();
    return stack[top--];
}
void showStack() // output values in the stack
{
    int i;
    if (top == -1) printf ("No value stored in the stack").\n");
    else {
        printf ("List of values stored in the stack\n");
        for (i = 0; i < top+1; i++) {
            printf("%03d : %c\n", i + 1, stack[i]);
        }
        printf("%d values are stored.\n",top);
    }
}
void main()
{
    int select=0;
    char a;
    while (select != 4) {
        printf("\n1. Put value in stack\n");
        printf("2. Pull value from stack\n");
        printf("3. Check the value stored in the stack\n");
        printf("4. Exit\n\n");
        printf ("Enter : ");
        scanf_s("%d", &select); 
        switch (select) {
        Case 1: // Save the entered value to the stack.
            printf("Enter a value to save: ");"
            a = getchar();
            push(a);
            break;
        Case 2: // Gets the integer value stored in the stack.
            printf("Import value : %c", pop(a));
            break;
        Case 3: // shows the values stored in the stack.
            showStack();
            break;
        }
    }
}

It's going to feel like I'm skipping one step instead of turning around like the while door I thought I don't think there's anything wrong, so what's the problem?

stack queue data-structure scanf

2022-09-20 22:31

1 Answers

If you search for scanf buffer problem, there are many articles.

After receiving it from scanf, there are still open characters in the input buffer, so if you move on to the getchar part immediately, the open character (\n) will enter the input for the value you want to save and move on to the next menu.

A very simple solution is to take the opening letter after scanf as getchar and empty it once.

scanf_s("%d", &select);
getchar();             // <===== !!!

switch(select) {
// ...

Also, when you receive the stack input value, you receive it with getchar, so you don't receive more than one character.


2022-09-20 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.