3

So I am trying to make a infix to postfix program in C but when I start entering the symbols, the loop ends at the first entry.

I am pretty sure it's a data type problem somewhere but I can't 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++){

    }*/     
}
Veske
  • 547
  • 1
  • 4
  • 15

1 Answers1

5

scanf() uses %c to reading characters, so your code should be

scanf(" %c", &input);

By adding a space after your %c specifier, you also consume any new line or space characters that might be added unintendedly, then correcting your loop issue.

As another thought, you will need to append an extra character onto your string: a null character, which is a '\0' character. This is why you will need to do s = malloc(max*sizeof(int) + 1);, so that you have space left for your '\0', which, in your case, you can add dynamically on your stackPush() function, like that:

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

Also, in your stackPush function, what you want is s[N] = item;, not s[N] += item;

More on C Strings

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
  • But will this add each character together in my s then? If I enter `asd+-+` then I want it to be in s like that later too as a string. – Veske Feb 26 '14 at 20:36
  • Right, got it allready. Can you also tell me please, why it outputs 1 instance less when it prints the stackpop. I enter 4 characters and it prints 3. When I did the same thing with numbers, it did not do so. – Veske Feb 26 '14 at 20:39
  • You made scanf like this now with your edit: " %c". It fixed the problems but I don't really get it, what did it do? – Veske Feb 26 '14 at 20:57
  • You consume the new line character `\n` that you typed before, when you read your `sum` value. So the first `scanf()` in your loop was reading it. By putting the space before the specifier, whe FIRST consume any trash that was hold onto the buffer and THEN read a character. What was happening before was the opposite, resulting in a bug. Is this clear enough? If not, I may update my answer :-) – Natan Streppel Feb 26 '14 at 20:59