The technique I would use is quite an advanced one - a finite state machine.
It is where you keep track of where you are in the expression (i.e. expecting an operator or a number) and act accordingly character by character.
I quickly wrote this up as an example of how it could be implemented:
Code:
#include <stdio.h>
enum state {
s_start_num,
s_num,
s_operator,
s_error,
s_end
};
enum state f_start_num(int c, int *v) {
if(c == ' ') {
return s_start_num;
}
*v = 0;
// A zero can not have any following digits, only an operator
if(c == '0') {
printf("Value of %d\n",*v);
return s_operator;
}
// A non-zero number
if(c >= '1' && c <= '9') {
*v = *v+c-'0';
return s_num;
}
// Unexpected input
printf("Expecting number\n");
return s_error;
}
enum state f_num(int c, int *v) {
// We are expecting digits
if(c >= '0' && c <= '9') {
*v = (*v * 10) + (c-'0');
return s_num;
}
// If we get anything but a digit, "unget() the character and then look for an operator
printf("Value of %d\n",*v);
ungetc(c,stdin);
return s_operator;
}
enum state f_operator(int c) {
switch(c) {
case ' ':
return s_operator; // Ignoring spaces
case '+':
case '-':
case '*':
case '/':
printf("Operator '%c'\n",c);
return s_start_num;
case '=':
printf("Equals sign\n");
return s_end;
}
printf("Expecting operator\n");
return s_error;
}
int main(int arg, char *argv[])
{
int state = s_start_num;
int v;
while(state != s_end) {
int c = getchar();
if(c == EOF)
state = s_error;
switch(state) {
case s_start_num: state = f_start_num(c, &v); break;
case s_num: state = f_num(c, &v); break;
case s_operator: state = f_operator(c); break;
default:
printf("Unknown state\n");
return 0;
}
}
}
Here's the some example output, breaking "13+33+0=" into it's parts.
Code:
$ echo "13+33+0=" | ./main
Value of 13
Operator '+'
Value of 33
Operator '+'
Value of 0
Equals sign
The super tricky bit is the ungetc() call, where it knows it has reached the end of the number but is not ready to decide what to do with the operator.
You will of cause need to do more than just print the parts of the expression.