So I understand that C is byte based. With that in mind, I'm working on a postfix implement, and I ran into a snag:
In postfix there are 4 operators + - * /. The program appends stdin to a linked list and implements postfix arithmetic on it. The problem:
I have integers where I am building character by character. This means I could conceivably have integer values in input that are ASCII equivalent to the operators.
How would I differentiate the two in C without using atoi?
Here's my code so far for reference. I'm also wondering if I need all the malloc calls I'm making or if I can use my 3 pointers to access the nodes I struct later on?
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
int main(){
struct node *head;
head = (struct node*)malloc( sizeof(struct node));
head->next = 0;
struct node *p;
p = (struct node*)malloc( sizeof(struct node));
p = head;
struct node *q;
q = (struct node*)malloc( sizeof(struct node));
q->next = NULL;
struct node *r;
r = (struct node*)malloc( sizeof(struct node));
r->next = NULL;
int c, d, e;
int val = 0;
int count = 0;
while((c = getchar()) != 'a' || ((c >= '0' && c <= 9) || c == '+' || c == '-'
|| c == '*' || c == '/' || c == ' ' || c == '\t' || c == '\n')){
if(c >= '0' && c <= '9'){
while(c >= '0' && c <= '9'){
val = val*10 + c - '0';
c = getchar();
}
c = val;
val = 0;
}
if(c != ' ' && c != '\t' && c != '\n'){
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->num = c;
p->next = newNode;
p = p->next;
}
}
//Bases
if(head->next == NULL)
return 1;
p = head->next;
q = p->next;
r = q->next;
while(r != NULL){
while(r != NULL && (r->num != '+' && r->num != '-' && r->num != '*' && r->num != '/'))
r = r->next;
if(r->num == '+' || r->num == '-' || r->num == '*' || r->num == '/'){
while(q->next != r){
p = q;
q = q->next;
}
if(r->num == '+')
p->num = p->num + q->num;
if(r->num == '-')
p->num = p->num - q->num;
if(r->num == '*')
p->num = p->num * q->num;
if(r->num == '/')
p->num = p->num / q->num;
p->next = r->next;
p = head->next;
q = p->next;
r = q->next;
}
}
// no valid operations left
if(p->num == '+' || p->num == '-' || p->num == '*' || p->num == '/')
return 1;
if(q->num == '+' || q->num == '-' || q->num == '*' || q->num == '/')
return 1;
p = head->next;
while(p != NULL){
printf("%d ", p->num);
p = p->next;
}
return 0;
}