1.显示功能
QString的显示效果不附带计算作用,如QString要显示字符1,则若先要显示“1 1”是QSting +=1
private:{
Ui::Widget *ui;
QString display;
}
void Widget::on_oneButton_clicked()
{
display += "1";
ui->mainLine->setText(display);
}//mainLine是创建的显示控件
这样多次按下oneButton时,显示在mainLine上的数据并不会累加成2、3、4、5,而是显示成“1”“11”“111”“1111”。
2.删除功能
引入 成员函数chop:stringA.chop(n)为从字符串stringA的尾部起删掉第n个数
QString str("LOGOUT\r\n");
str.chop(2);
// str == "LOGOUT"
QString str("Qt5.12.0");
str.chop(3);
// str == "Qt5.1"
3.四则运算算法
假设输入“1+2*3/(4-9)",对于程序来说都是string字符类型(为了能在设计好的屏幕上显示所以用了string类型)仅作为字符是没有含义的,需要将字符串:
“1+2*3/(4-9)"
变为包含数学含义的
‘数字1 加 数字2 乘 数字3 除 左括号 数字4 减 数字9 右括号’
这个过程叫做tokenize(符号化),也就是字符解析
在部分高级语言如python等中,语言系统自带类似eval函数来自动进行字符解析
你输入“1+2*3/(4-9)"时,python会认出你是在输入具有数学含义的符号,但在c++中tokenize需要单独进行
//QString转换成char指针
QByteArray ba;
ba.append(display);//把QString的display转换成QByteArray
strcpy(opt,ba.data());
//把opt复制给QByteArray的ba,即把ba转换成cosnt char *以达成把display转成char*
//这里的用到的strcpy需要添加头文件string.h
算法使用双栈式运算,外设运算优先级以分辨“()” > 乘除 > 加减
设置数字栈和运算符栈两个栈
QStack<int> s_num,s_opt; //创建数字栈和操作符栈
char opt[128] = {0};
int i = 0,tmp = 0,num1,num2;
设置四则运算启动的初始条件
while (opt[i] != '\0' || s_opt.empty() != true)
{
if(opt[i]>= '0' && opt[i] <= '9')
{
tmp = tmp * 10 + opt[i] - '0';
i++;
if(opt[i]< '0' || opt[i] > '9')
{
s_num.push(tmp);
tmp = 0;
}
}
操作符判断主体
else //操作符
{
if(s_opt.empty() == true || Priority(opt[i]) > Priority(s_opt.top()) ||
(s_opt.top() == '(' && opt[i] != ')' ))
{
s_opt.push(opt[i]);
i++;
continue;
}
if(s_opt.top() == '(' && opt[i] == ')')
{
s_opt.pop();
i++;
continue;
}
if(Priority(opt[i]) <= Priority(s_opt.top()) || (opt[i] == ')' &&
s_opt.top() != '(') || (opt[i] == '\0' && s_opt.empty() != true))
{
char ch = s_opt.top();
s_opt.pop();
......
}
四则运算主体
{
char ch = s_opt.top();
s_opt.pop();
switch(ch)
{
case '+':
num1 = s_num.top();
s_num.pop();
num2 = s_num.top();
s_num.pop();
s_num.push(num1 + num2);
break;
case '-':
num1 = s_num.top();
s_num.pop();
num2 = s_num.top();
s_num.pop();
s_num.push(num1 - num2);
break;
case '*' :
num1 = s_num.top();
s_num.pop();
num2 = s_num.top();
s_num.pop();
s_num.push(num1 * num2);
break;
case '/' :
num1 = s_num.top();
s_num.pop();
num2 = s_num.top();
s_num.pop();
s_num.push(num1 / num2);
break;
}
}
运算结束后,由于双栈操作均使用int类型来完成计算,计算完成后需要将int型转变为QString型以显示在设定好的“屏幕上”,使用
QString::number(n);
//包含在QString中的成员函数number
其作用是数字n(int double float等)转变为字符型
while (opt[i] != '\0' || s_opt.empty() != true)
{
if(opt[i]>= '0' && opt[i] <= '9')
{.....}
else //操作符
{.....}
ui->mainLine->setText(QString::number(s_num.top()));
display.clear();
}