S
Simon Morgan
I'm trying to write a function to parse a Reverse Polish Notation string
from stdin and return 1 token at a time. For those of you who are unaware
an RPN string looks like this:
1 2 + 4 * 3 +
With each number being read and pushed onto a stack and, when an operator
is encountered, each number on the stack is popped off and calculated
using that operator and the result pushed onto the stack.
The problem I'm having is differentiating between for example, the +
character and the number 43. Here's what I have so far:
#include <stdio.h>
int read_token(void) {
int token, next_token;
while ((token = getchar()) != EOF) {
if (token == ' ' || token == '\n') {
continue;
}
if (token == '+' || token == '-' || token == '*' || token == '/') {
break;
} else {
while ((next_token = getchar()) != ' ' && next_token != EOF) {
token *= 10;
token += next_token;
}
break;
}
}
return token;
}
What's the conventional wisdom on overcoming the ambiguity between
characters and numbers in C?
Thanks.
from stdin and return 1 token at a time. For those of you who are unaware
an RPN string looks like this:
1 2 + 4 * 3 +
With each number being read and pushed onto a stack and, when an operator
is encountered, each number on the stack is popped off and calculated
using that operator and the result pushed onto the stack.
The problem I'm having is differentiating between for example, the +
character and the number 43. Here's what I have so far:
#include <stdio.h>
int read_token(void) {
int token, next_token;
while ((token = getchar()) != EOF) {
if (token == ' ' || token == '\n') {
continue;
}
if (token == '+' || token == '-' || token == '*' || token == '/') {
break;
} else {
while ((next_token = getchar()) != ' ' && next_token != EOF) {
token *= 10;
token += next_token;
}
break;
}
}
return token;
}
What's the conventional wisdom on overcoming the ambiguity between
characters and numbers in C?
Thanks.