Write a simple desktop calculator to handle the two-dollar operation
//14_44.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>#include<functional>#include<string>#include<map>#include<utility>#include<algorithm>using namespacestd;//function Call object that defines ' + 'structADD {int operator()(intIintj) {returni +J;}};//lambda expression that defines '-'Auto Minuse = [] (intIintj) {returnIJ;};//functions that define ' * 'intMultiplies (intIintj) { returni*J;}//simple two-dollar four expressionintArithmatic (string&1) { //defines a mapping that holds the relationship between the operator and the calling objectmap<Char, function<int(int,int) >> Ma = { {'+', Add ()}, {'-', Minuse}, {'*', multiplies},//template function object defined in functional{'/',divides<int>()}, {'%',modulus<int>()} }; //finding operators in a stringAuto Opration = find_if (S.begin (), S.end (), [] (Charch) { returnch = ='+'|| ch = ='-'|| ch = ='*'|| ch = ='/'|| ch = ='%';}); //If the operator is at the beginning or end or is not found, it is an incorrect expression if(Opration = = S.begin () | | Opration = = S.end () | | opration==++S.end ()) { //throws a run-time exception ThrowRuntime_error ("The expression inputed is wrong!"); } //gets the length of the integer preceding the expressionsize_t len1 = opration-S.begin (); //get the length of an integer after an expressionsize_t len2 = S.end ()-Opration-1; //get an integer before an expression stringSTR1 = S.substr (0, LEN1); //get an integer after an expression stringstr2 = s.substr (Len1 +1, Len2); //An auxiliary string used to determine whether an integer expression is correct stringstr ="0123456789"; //if a character other than 0123456789 is found in a two integer string, an error is indicated if(Str1.find_first_not_of (str)! =string:: NPOs | | Str2.find_first_not_of (str)! =string:: NPOs) { //throws a run-time error ThrowRuntime_error ("The expression inputed is wrong!"); } //converts a two integer string to an integer inti = Stoi (str1), j =Stoi (STR2); //call the corresponding callable object to get the result intRET = ma[*Opration] (I, j); returnret;}intMain () {stringstr; while(1) {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 0;}
C++primer Exercise 14.44