Skip to content

Instantly share code, notes, and snippets.

@samescolas
Created May 20, 2017 16:11
Show Gist options
  • Save samescolas/6fe051859bd3a5e56694ea33fb0f69b7 to your computer and use it in GitHub Desktop.
Save samescolas/6fe051859bd3a5e56694ea33fb0f69b7 to your computer and use it in GitHub Desktop.
rpn_calculator for exam
#include "rpn_calc.h"
int is_op(char *str)
{
if (*str == '+' || *str == '-' || *str == '/' || *str == '*' || *str == '%')
{
if (*(str + 1) && *(str + 1) != ' ')
return (0);
else
return (1);
}
return (0);
}
int is_numeric(char *str)
{
if (*str == '-')
++str;
while (*str && *str != ' ')
{
if (*str >= '0' && *str <= '9')
++str;
else
return (0);
}
return (1);
}
int ft_calc(int a, int b, char op)
{
if (op == '+')
return (a + b);
else if (op == '-')
return (a - b);
else if (op == '/')
return (a / b);
else if (op == '*')
return (a * b);
else if (op == '%')
return (a % b);
return (0);
}
void rpn_calculate(char *str)
{
int nums[256];
int num_vals;
int ix;
ix = 0;
num_vals = 0;
while (str[ix])
{
if (is_op(&str[ix]))
{
if (num_vals >= 2)
{
if (nums[num_vals - 1] == 0 && (str[ix] == '/' || str[ix] == '%'))
{
printf("Error\n");
return ;
}
nums[num_vals - 2] = ft_calc(nums[num_vals - 2], nums[num_vals - 1], str[ix]);
--num_vals;
if (str[ix + 1])
ix += 2;
else
break ;
}
else
{
printf("Error\n");
return ;
}
}
else if (is_numeric(&str[ix]))
{
nums[num_vals++] = atoi(&str[ix]);
while (str[ix] && str[ix] != ' ')
++ix;
if (str[ix])
++ix;
}
else
{
printf("Error\n");
return ;
}
}
if (num_vals == 1)
printf("%d\n", nums[0]);
else
printf("Error\n");
}
#include "rpn_calc.h"
int main(int argc, char **argv)
{
if (argc == 2)
rpn_calculate(argv[1]);
else
printf("Error\n");
}
#include <stdlib.h>
#include <stdio.h>
void rpn_calculate(char *str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment