I have a C program that converts postfix notation into an answer, so for "2 2 +" it would print 4, for "2 4 + 3 / 6 +" it would print 8. However, when I do "2 4 ^ 2 * 5 % 2", it has a problem with the "" since it take the bin I'm in to account and adds file names into the command line arguments. I'll attach my code that I have going, but my question is, is there anyway to avoid having the "" in the command line mess with the test of the arguments.
PS, someone told me that by putting the * in quotation marks in the command line, like so:
./a.out 2 4 ^ 2 "*" 5 % 2 -
would work, and it hasn't. so any ideas around this?
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct stack {
int top;
int items[100];
} stack;
void initializeStack(stack* p);
void push(stack* p, int val);
int pop(stack* p);
int main(int argc, char** argv) {
int i, a, b;
int val = 0;
stack ph;
initializeStack(&ph);
//for(i=1; i<argc; i++)
//printf("%s\n", argv[i]);
for(i=1; i<argc; i++) {
if(strcmp(argv[i], "*") == 0) {
a = pop(&ph);
b = pop(&ph);
val = a*b;
push(&ph, val);
}
else if(strcmp(argv[i], "/") == 0) {
a = pop(&ph);
b = pop(&ph);
val = b/a;
push(&ph, val);
}
else if(strcmp(argv[i], "+") == 0) {
a = pop(&ph);
b = pop(&ph);
val = a+b;
push(&ph, val);
}
else if(strcmp(argv[i], "-") == 0) {
a = pop(&ph);
b = pop(&ph);
val = b-a;
push(&ph, val);
}
else if(strcmp(argv[i], "^") == 0) {
a = pop(&ph);
b = pop(&ph);
val = (int)pow(a,b);
push(&ph, val);
}
else if(strcmp(argv[i], "%") == 0) {
a = pop(&ph);
b = pop(&ph);
val = b%a;
push(&ph, val);
}
else {
push(&ph, atoi(argv[i]));
}
}
printf("%d\n", pop(&ph));
return 0;
}
void initializeStack(stack* p) {
p->top = 0;
}
void push(stack* p, int val) {
p->top++;
p->items[p->top] = val;
}
int pop(stack* p) {
int y;
y = p->items[p->top];
p->items[p->top] = 0;
(p->top)--;
return y;
}
Try this: \*. Much like in C you need to provide an escape character for arguments that the command line recognizes. (where "\" is the escape).
Disclaimer: \ is for GNU/Linux anyway (and as a side note, also for Stack answers... You need two \'s in order to print one \).