From a4e5a100b3342a408bffd0cb9fe30ccb7dccabda Mon Sep 17 00:00:00 2001 From: Camille Chauvet Date: Wed, 4 Oct 2023 11:21:15 +0000 Subject: [PATCH] ex01: init --- ex01/Makefile | 26 ++++++++++++++ ex01/src/RPN.cpp | 4 +++ ex01/src/main.cpp | 87 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 ex01/Makefile create mode 100644 ex01/src/RPN.cpp create mode 100644 ex01/src/main.cpp diff --git a/ex01/Makefile b/ex01/Makefile new file mode 100644 index 0000000..7f950fe --- /dev/null +++ b/ex01/Makefile @@ -0,0 +1,26 @@ +CXX := c++ +CXXFLAGS := -std=c++98 -Wall -Wextra -Werror -g +SRCDIR := src +OBJDIR := obj +NAME := ex01 + +SRCS := $(wildcard $(SRCDIR)/*.cpp) +OBJS := $(patsubst $(SRCDIR)/%.cpp,$(OBJDIR)/%.o,$(SRCS)) + +all: $(NAME) + +$(OBJDIR)/%.o: $(SRCDIR)/%.cpp + mkdir -p obj + $(CXX) $(CXXFLAGS) -c $< -o $@ + +$(NAME): $(OBJS) + $(CXX) $(CXXFLAGS) $^ -o $@ + +clean: + rm -rf $(OBJDIR) + +fclean: clean + rm -fr $(NAME) + +re: fclean + @make --no-print-directory all diff --git a/ex01/src/RPN.cpp b/ex01/src/RPN.cpp new file mode 100644 index 0000000..dfaeecb --- /dev/null +++ b/ex01/src/RPN.cpp @@ -0,0 +1,4 @@ +#include +#include + + diff --git a/ex01/src/main.cpp b/ex01/src/main.cpp new file mode 100644 index 0000000..08f173f --- /dev/null +++ b/ex01/src/main.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include +#include +#include + +int substraction(int a, int b) { return (a - b); } +int addition(int a, int b) { return (a + b); } +int division(int a, int b) { return (a / b); } +int multiplication(int a, int b) { return (a * b); } + +int calculate(std::stack& nums, std::stack& operators) +{ + if (nums.size() < 2 || operators.size() == 0) + return 0; + + int ret; + int a = nums.top(); + nums.pop(); + int b = nums.top(); + nums.pop(); + + switch (operators.top()) { + case '+': + ret = addition(a, b); + break; + case '-': + ret = substraction(a, b); + break; + case '*': + ret = multiplication(a, b); + break; + case '/': + if (b == 0) + return 1; + ret = division(a, b); + break; + } + operators.pop(); + nums.push(ret); + return 0; +} + +int main(int ac, char** av) +{ + if (ac != 2) + { + std::cout << "error: args" << std::endl; + return 1; + } + + std::stack nums; + std::stack operators; + + for (size_t i = 0; av[1][i] != '\0'; i++) + { + if (av[1][i] == ' ') + continue; + if (std::isdigit(av[1][i])) + nums.push(av[1][i] - '0'); + else if (std::strchr("/+-*", av[1][i]) != NULL) + operators.push(av[1][i]); + else + { + std::cout << "error: '" << av[1][i] << "' unknown char" << std::endl; + return 1; + } + if (calculate(nums, operators)) + { + std::cout << "error: division by 0" << std::endl; + return 1; + } + } + if (nums.size() != 1) + { + std::cout << "error: too many numbers" << std::endl; + return 1; + } + if (operators.size() != 0) + { + std::cout << "error: too manu operators" << std::endl; + return 1; + } + std::cout << nums.top(); + return 0; +}