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?
getchardoes. 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.isdigit(ch)instead of the magic number range check. Also in(int)ch - (int)'0'both operands are alreadyinttype, soch - '0'is good.