I am trying to do an RPN where my not constant argv vector stores and retrieves results of calculations by replacing an operator with the result of the operation: argv[0]="2"; argv[1]="3"; argv[2]="+" ==> argv[0]="2";argv[1]="3";argv[2]=5 My code works for simple RPN input -- input with a maximum of one operation; it fails at nested operations because when it reads argv[n] it finds nothing in it, so it sees it as zero. Can you guys help? Here's the code:
/*
* Ahmed AlJehairan
* Github: aj326
* Description: Reverse Polish Calc. Usage ./expr n1 n2 op
*/
#include <stdio.h>
#include <stdlib.h>
#define DEBUG 1
//Will implement error checking later:
/*
Errors to check for:
arg starts with letter
first arg not a number
check at least two arg for binary ops
*/
int main(int argc, char *argv[])
{
char **s = argv;
int len = argc;
if (argc < 3)
{
printf("At least 2 arguments\n");
return 1;
}
if (--argc) argv++;
int val;
while (argc--)
{
switch (**argv)
{
case '+': ; val = atoi(*(argv - 2)) + atoi(*(argv - 1)); snprintf (*argv, sizeof(int), "%d", val); if (DEBUG) printf("after arith *argv %s \n", *argv); break;
case '=': ; val = atoi(*(argv - 2)) == atoi(*(argv - 1)); snprintf (*argv, sizeof(int), "%d", val); if (DEBUG) printf("after arith *argv %s \n", *argv); break;
case '-': ; val = atoi(*(argv - 2)) - atoi(*(argv - 1)); snprintf (*argv, sizeof(int), "%d", val); if (DEBUG) printf("after arith *argv %s \n", *argv); break;
case '*': ; val = atoi(*(argv - 2)) * atoi(*(argv - 1)); snprintf (*argv, sizeof(int), "%d", val); if (DEBUG) printf("after arith *argv %s \n", *argv); break;
case '/': ; val = atoi(*(argv - 2)) / atoi(*(argv - 1)); snprintf (*argv, sizeof(int), "%d", val); if (DEBUG) printf("after arith *argv %s \n", *argv); break;
case '%': ; val = atoi(*(argv - 2)) % atoi(*(argv - 1)); snprintf (*argv, sizeof(int), "%d", val); if (DEBUG) printf("after arith *argv %s \n", *argv); break;
}
if (DEBUG)
{
int i;
for (i = 0; i < len; ++i)
{
printf("%s\t", s[i]);
}
printf("\n");
}
argv++;
}
printf("%s\n", *--argv);
return 0;
}