0

I have the following code (s1 and s2 are stacks). If the character is an operator it is stored in stack s2, if it is a digid from 0 to 9 it is stored in s1.

int ch;
ch = getchar();

while((ch=getchar())!='\n')
{
    print("%d\n", ch);

    if(ch>47 && ch<58)
    {
        push((int)ch - (int)'0', &s1);
    }
    else
    {

        push(ch, &s2);
    }
}

The problem is if the input is "+12" then the ASCII code for 1 and 2 are printed but the ASCII code for the '+' operator is not.

But If the input is "++12" then the ASCII code for one of the '+' is printed and then for the 1 and for 2.

So how this code really works?

2
  • 1
    Think about what getchar does. When you enter the while loop for the first time, how often has it been called? Your problem has nothing to do with whether the read char is an operator or a digit. Commented Mar 5, 2020 at 17:44
  • A couple of asides: you can use isdigit(ch) instead of the magic number range check. Also in (int)ch - (int)'0' both operands are already int type, so ch - '0' is good. Commented Mar 5, 2020 at 17:55

1 Answer 1

1

You are doing an initial getchar() call before your while loop, so you're always missing the first input.
Try removing it and it should work !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.