33,311
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
using std::string;
static const size_t npos = -1;
//不知道是不是因为对一个值在不同函数反复引用且不改变变量导致崩溃的。
void opperation(string &_expression, string &_str);
void times_divide(string &_expression, string &_str);
void plus_minus(string &_expression, string &_str);
void renew(string &_str, int _num, int i, int j);
void opperation(string &_expression, string &_str)
{
times_divide(_expression, _str);
}
void times_divide(string &_expression, string &_str)
{
int num, num_1, num_2;
int temp_1, temp_2, i = 2, j = 2;
if (_str.find_first_of('*')!=_str.npos)
//如果首先找到*号则进入判定
{
temp_1 = _str.find_first_of('*')-2;
//temp_1是*号靠左相邻的运算符,暂时考虑两运算符之间的数据为1位
temp_2 = _str.find_first_of('*')+2; //类似上
while (_str[_str.find_first_of('*')-i]>=48 && _str[_str.find_first_of('*')-i]<=57)
//当两运算符之间的数据不是一位时,两temp分别向两边推移
{
temp_1--;
i--;
}
while (_str[_str.find_first_of('*')+j]>=48 && _str[_str.find_first_of('*')+j]<=57)
{
temp_2++;
j++;
}
num_1 = atoi(_str.substr(temp_1+1, _str.find_first_of('*')-temp_1).c_str());
//截取*号两边的两个数据并转换为整形
num_2 = atoi(_str.substr(_str.find_first_of('*')+1, temp_2-_str.find_first_of('*')-2).c_str());
num = num_1*num_2;
//计算结果,实际上后面就是用结果替换掉这步乘法运算
renew(_str, num, temp_1, temp_2);
//字符串更新,减少掉一个*号,直接代入结果,
times_divide(_expression, _str);
//用递归实现逐步减少*号至没有
}
else if (_str.find_first_of('/')!=_str.npos) //这个是/号的,类似上
{
temp_1 = _str.find_first_of('/')-2;
temp_2 = _str.find_first_of('/')+2;
while (_str[_str.find_first_of('/')-i]>=48 && _str[_str.find_first_of('/')-i]<=57)
{
temp_1--;
i--;
}
while (_str[_str.find_first_of('/')+j]>=48 && _str[_str.find_first_of('/')+j]<=57)
{
temp_2++;
j++;
}
num_1 = atoi(_str.substr(temp_1+1, _str.find_first_of('/')-temp_1).c_str());
num_2 = atoi(_str.substr(_str.find_first_of('/')+1, temp_2-_str.find_first_of('/')-2).c_str());
num = num_1*num_2;
renew(_str, num, temp_1, temp_2);
times_divide(_expression, _str);
}
else //如果没有*和/就结束递归
{
return;
}
}
void plus_minus(string &_expression, string &_str)
{//这个是加减部分的,暂不考虑
}
void renew(string &_str, int _num, int i, int j)
{
stringstream ss; //这一大串是将整形转为string
string temp;
ss << _num;
ss >> temp;
_str = _str.substr(0, i) + temp + _str.substr(j); //连接成新的字符串
}
int main(void)
{
string expression("123456"); //这个暂时没用,请忽略
string str("1*2+3/4");
opperation(expression, str);
return 0;
}
while(_str[_str.find_first_of('*')-i]>=48 && _str[_str.find_first_of('*')-i]<=57)
这句话,你取出了*位置,然后减2. 小于0了。c++里string对象木有小于0的下标操作啊 _str[_str.find_first_of('*')-i]>=48
//_str.find_first_of('*')-i 是一个复数 -1