编写一个简单的桌面计算器使其处理二元运算
// 14_44.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include<iostream>
#include<functional>
#include<string>
#include<map>
#include<utility>
#include<algorithm> using namespace std; //定义'+'的函数调用对象
struct Add
{
int operator()(int i, int j) { return i + j; }
}; //定义'-'的lambda表达式
auto Minuse = [](int i, int j) {return i - j;}; //定义'*'的函数
int Multiplies(int i, int j)
{
return i*j;
} //简单二元四则表达式
int arithmatic(string &s)
{
//定义一个映射,用来保存运算符和调用对象的关系
map<char, function<int(int, int)>> ma =
{
{'+',Add()},
{'-',Minuse},
{'*',Multiplies},
//定义在functional中的模板函数对象
{'/',divides<int>()},
{'%',modulus<int>()}
};
//找出string中的运算符
auto Opration = find_if(s.begin(), s.end(), [](char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%';});
//如果运算符在开头或者结尾或者没有找到,则是一个错误的表达式
if (Opration == s.begin() || Opration == s.end()||Opration==++s.end())
{
//抛出一个运行时异常
throw runtime_error("the expression you have inputed is wrong!");
}
//得到表达式前面的整数的长度
size_t len1 = Opration - s.begin();
//得到表达式后面的整数的长度
size_t len2 = s.end() - Opration - ;
//得到表达式前面的整数
string str1 = s.substr(, len1);
//得到表达式后面的整数
string str2 = s.substr(len1 + , len2);
//辅助字符串用来判断整数的表达式是否正确
string str = "";
//如果在两个整数字符串中发现了除0123456789之外的其他字符,则表明错误
if (str1.find_first_not_of(str) != string::npos || str2.find_first_not_of(str) != string::npos)
{
//抛出一个运行时错误
throw runtime_error("the expression you have inputed is wrong!");
}
//将两个整数字符串转换为整数
int i = stoi(str1), j = stoi(str2);
//调用对应的可调用对象,得到结果
int ret = ma[*Opration](i, j);
return ret;
} int main()
{
string str;
while ()
{
cout << "please input your expression:";
cin >> str;
cout << endl;
try
{
cout << arithmatic(str) << endl;
}
catch (runtime_error e)
{
cerr << e.what() << endl;
cout << "please input Y to continue or N to quit:";
cin >> str;
if ("Y" == str)
continue;
else break;
}
break;
}
return ;
}