C - circuit terminates unexpectedly

So, I'm trying to make an infix for a postfix program in C, but when I start typing characters, the loop ends in the first entry.

I am sure that the data type problem is somewhere, but I cannot figure out where ..

Here is the code:

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

static int N;
static char *s;

void stackinit(int max){
    s = malloc(max*sizeof(int));
    N = 0;
}

int stackempty(){
    if(N==0)
        return(1);
    else
        return(0);
}

void stackpush(char item){
    s[N] += item;
    N++;
}

int stackpop(){
    N--;
    return(s[N]);
}

int priority(char x){
    if(x == '+' || x == '-')
        return(0);
    if(x == '*' || x == '/')
        return(1);
}
int main(void){
    int i,sum;
    char input;

    printf("Infix to Postfix\n");
    printf("How many characters will you enter?");
    scanf("%d", &sum);
    stackinit(sum);

    for(i = 0; i < sum; i++){
        printf("Enter character: ");
        scanf("%s", &input);
        stackpush(input);
    }
    while(!stackempty()){
        printf("%d ", stackpop());
    }
    /*for(i = 0; i < sum; i++){

    }*/     
}
+3
source share
1 answer

scanf()uses %cto read characters, so your code should be

scanf(" %c", &input);

By adding a space after your qualifier %c, you also consume any new line or space characters that might be added unintentionally, and then fixing the loop problem.

: , '\0'. s = malloc(max*sizeof(int) + 1);, '\0', stackPush(), :

void stackpush(char item){
    s[N++] = item;
    s[N] = '\0';
}

, stackPush s[N] = item;, s[N] += item;

C

+5

All Articles