This blog is used to record a calculator for my own use C ++ implementation, the goal is to complete the four arithmetic operations with parentheses, and optimized at a later stage with the factory design pattern.
Part 1:calculate 1+1=2
To achieve such a calculation formula, you only need to use a string split, initially tried stringstream to first read a whole string of "1 + 2", and then create two temporary variables int and a char, >> read into use, but found reading in the middle of char is ignored
string s ="12+34"; // stringstream ss(s); // int n1,n2,c; // ss>>n1>>c>>n2;//c is 34 ,the '+' is ignored
I then to switch to the substr dividing, substr two parameters, the beginning of a string separated position and the other is the length of the string, the second parameter is the default value NPoS, i.e. end of the string.
int i =0; while(isdigit(s[i])) { ++i;//pos } // int n =atof("22.0"); // cout<<n; //float d = atof(s.substr(0,i).c_str()); cout<<cal( atof(s.substr(0,i).c_str()) , atof(s.substr(i+1).c_str()) ,s[i])<<endl;
//string to const char*
//use c_str() 函数
Such a simple run out of 1 + 1 = 2 a! But this procedure to change a lot of trouble, there is no way to adapt to 1 + 1 + 1 = 3, there is no priority operation, wait for the next part we come back to do new features.