Skip to content

Instantly share code, notes, and snippets.

@Dabbler65
Forked from DreamVB/rpn.cpp
Created January 29, 2018 10:00
Show Gist options
  • Save Dabbler65/47002094487f40297af5b69715457a24 to your computer and use it in GitHub Desktop.
Save Dabbler65/47002094487f40297af5b69715457a24 to your computer and use it in GitHub Desktop.
C++ Reverse Polish Notation calulator
.vs/RPN/v14/.suo
Debug/RPN.exe
Debug/RPN.log
Debug/RPN.pdb
Debug/RPN.tlog/CL.command.1.tlog
Debug/RPN.tlog/CL.read.1.tlog
Debug/RPN.tlog/CL.write.1.tlog
*.tlog
*.ilk
*.idb
Debug/vc140.pdb
*.obj
RPN.VC.db
RPN.VC.VC.opendb
RPN.vcxproj.filters
*.exe
*.pdb
*.log
// Reverse Polish notation demo
// Basic calulator for RPN expression only + / * - is supported.
// Allows ints and floats.
// By DreamVB ([email protected]) 20:08 26/09/2016
// Forked by Tom240965 https://gist.github.com/Tom240965/47002094487f40297af5b69715457a24
#include <iostream>
#include <string>
#include <stack>
#include <stdexcept>
namespace Ben
{
#define MAX_STACK 100
float _stack[MAX_STACK];
int tos = 0;
bool Full(){
return tos >= MAX_STACK - 1;
}
bool Empty(){
return tos == 0;
}
void Push(float value){
if (Full()){
return;
}
tos++;
_stack[tos] = value;
}
float Pop(){
float t = _stack[tos];
tos--;
return t;
}
bool IsOp(char c)
{
//Check for operators.
switch (c)
{
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}
double RPN(const std::string& expression)
{
size_t i = 0;
float v1, v2, ret;
v1 = ret = v2 = 0.0;
std::string tok;
while (i < expression.length()) {
//Skip white space
while (isspace(expression[i])) {
i++;
}
//Check for digits and .
if (isdigit(expression[i]) || expression[i] == '.')
{
while (isdigit(expression[i]) || expression[i] == '.')
{
tok += expression[i];
i++;
}
//Push on stack number.
Push((float)atof(tok.c_str()));
tok = "";
}
//Check for operator
else if (IsOp(expression[i])) {
if (expression[i] == '+') {
v1 = Pop();
v2 = Pop();
ret = (v1 + v2);
}
if (expression[i] == '-') {
v1 = Pop();
v2 = Pop();
ret = v2 - v1;
}
if (expression[i] == '*') {
v1 = Pop();
v2 = Pop();
ret = (v1 * v2);
}
if (expression[i] == '/') {
v1 = Pop();
v2 = Pop();
ret = (v2 / v1);
}
//INC Counter
i++;
//Push result onto stack
Push(ret);
}
else
throw std::runtime_error("Invaild Expression.");
}
//Return answer
return Pop();
}
}
namespace Tom
{
double RPN(const std::string& expression)
{
std::stack<float> numbers;
size_t i = 0;
float v1, v2, ret;
v1 = ret = v2 = 0.0;
std::string tok;
while (i < expression.length())
{
//Skip white space
while (isspace(expression[i]))
{
i++;
}
//Check for digits and .
if (isdigit(expression[i]) || expression[i] == '.')
{
while (isdigit(expression[i]) || expression[i] == '.')
{
tok += expression[i];
i++;
}
//Push on stack number.
//Push(atof(tok.c_str()));
numbers.push((float)atof(tok.c_str()));
tok = "";
}
//Check for operator
else if (Ben::IsOp(expression[i]))
{
if (expression[i] == '+')
{
if (numbers.size() < 2)
throw std::runtime_error("Error in expression - not 2 numbers in stack");
v1 = numbers.top();
numbers.pop();
v2 = numbers.top();
numbers.pop();
ret = (v1 + v2);
}
if (expression[i] == '-')
{
if (numbers.size() < 2)
throw std::runtime_error("Error in expression - not 2 numbers in stack");
v1 = numbers.top();
numbers.pop();
v2 = numbers.top();
numbers.pop();
ret = v2 - v1;
}
if (expression[i] == '*')
{
if (numbers.size() < 2)
throw std::runtime_error("Error in expression - not 2 numbers in stack");
v1 = numbers.top();
numbers.pop();
v2 = numbers.top();
numbers.pop();
ret = (v1 * v2);
}
if (expression[i] == '/')
{
if (numbers.size() < 2)
throw std::runtime_error("Error in expression - not 2 numbers in stack");
v1 = numbers.top();
numbers.pop();
v2 = numbers.top();
numbers.pop();
ret = (v2 / v1);
}
//INC Counter
i++;
//Push result onto stack
numbers.push(ret);
}
else
{
std::cout << "Invaild Expression." << std::endl;
break;
}
}
//Return answer
if (numbers.size() != 1)
throw std::runtime_error("Stack doesn't contain result");
return numbers.top();
}
}
int main()
{
using std::cout;
using std::endl;
try
{
system("title RPN Calulator Demo");
//Infix == (4 * (12 + 3) / 2 * (5 + 5) - (100 * 2))/2 Answer 50
std::string expr = "4 12 3 + * 2 / 5 5 + * 100 2 * - 2 /";
cout << "Expression : " << expr.c_str() << endl;
cout << "Answer : " << Tom::RPN(expr) << endl << endl;
cout << "Expression : " << "22 7 /" << endl;
cout << "PI : " << Tom::RPN("22 7 /") << endl;
system("pause");
}
catch (const std::exception& ex)
{
std::cerr << "Error: " << ex.what() << "\n\n";
return 1;
}
#ifdef _DEBUG
system("pause");
#endif
// return 0; not needed since default
}

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RPN", "RPN.vcxproj", "{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Debug|x64.ActiveCfg = Debug|x64
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Debug|x64.Build.0 = Debug|x64
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Debug|x86.ActiveCfg = Debug|Win32
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Debug|x86.Build.0 = Debug|Win32
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Release|x64.ActiveCfg = Release|x64
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Release|x64.Build.0 = Release|x64
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Release|x86.ActiveCfg = Release|Win32
{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{407C65B1-B7F2-4FB2-A5AE-7A9796ABBADC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
<TreatWarningAsError>true</TreatWarningAsError>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<TreatWarningAsError>true</TreatWarningAsError>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="rpn.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment