C++实现简易的计算器,对简单的字符串求值

#include <iostream>
#include <string>
using namespace std;

class solution
{
public:
	int calculate(string s)
	{
		int result = 0, inter_res = 0, num = 0;
		char op = '+';
		char ch;
                //找到第一个不为空的字符
		for (int pos = s.find_first_not_of(' '); pos < s.size(); pos = s.find_first_not_of(' ', pos))
		{
			ch = s[pos];
                        //判断是否是数字
			if (ch >= '0' && ch <= '9')
			{
				int num = ch - '0';
                                //判断下一个字符是否也是数字
				while (++pos < s.size() && s[pos] >= '0' && s[pos] <= '9')
					num = num * 10 + s[pos] - '0';
				switch (op)
				{
				case '+':
					inter_res += num;
					break;
				case'-':
					inter_res -= num;
					break;
				case'*':
					inter_res *= num;
					break;
				case'/':
					inter_res /= num;
					break;
				}
			}
			else
			{
				if (ch == '+' || ch == '-')
				{
					result += inter_res;
					inter_res = 0;
				}
				op = s[pos++];
			}
		}
		return result + inter_res;
	}
};

 测试及结果如下:


int main()
{
	solution so;
	string str = "12+15*9-2/10";
	int result = so.calculate(str);
	cout << result << endl;
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/Color_Blind/article/details/81507375
今日推荐