code:
#include <iostream>
#include <string>
#include <map>
#include <cctype>
#include <sstream>
using namespace std;
enum token_value {
NAME, NUMBER, END,
PLUS='+', MINUS='-', MUL='*', DIV='/',
PRINT=';', ASSIGN='=', LP='(', RP=')'
};
token_value curr_tok = PRINT;
double expr(bool get)
{
double term(bool);
double left = term(get);
for (;;)
switch (curr_tok){
case PLUS:
left += term(true);
break;
case MINUS:
left -= term(true);
break;
default:
return left;
}
}
double term(bool get)
{
double error(const string&);
double prim(bool);
double left = prim(get);
for (;;)
switch(curr_tok) {
case MUL:
left *= prim(true);
break;
case DIV:
if (double d = prim(true)) {
left /= d;
break;
}
return error("divide by 0");
default:
return left;
}}
double number_value;
string string_value;
double prim(bool get)
{
map<string,double>table;
double error(const string&);
token_value get_token();
double expr(bool);
if(get) get_token();
switch(curr_tok) {
case NUMBER:
{
double v = number_value;
get_token();
return v;
}
case NAME:
{
double& v = table[string_value];
if(get_token() == ASSIGN) v = expr(true);
return v;
}
case MINUS:
return -prim(true);
case LP:
{
double e = expr(true);
if(curr_tok != RP) return error(") expected");
get_token();
return e;
}
default:
return error("primary expected");
}
}
token_value get_token()
{
double error(const string&);
char ch;
do {
if(!cin.get(ch)) return curr_tok = END;
} while(ch != '\n' && isspace(ch));
switch (ch){
case ';':
case '\n':
return curr_tok = PRINT;
case '*':
case '/':
case '-':
case '+':
case '(':
case ')':
case '=':
return curr_tok = token_value(ch);
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
cin.putback(ch);
cin >> number_value;
return curr_tok=NUMBER;
default:
if (isalpha(ch)) {
string_value = ch;
while (cin.get(ch) && isalnum(ch)) string_value.push_back(ch);
cin.putback(ch);
return curr_tok=NAME;
}
}
error ("bad token");
return curr_tok = PRINT;
}
int no_of_errors;
double error(const string& s)
{
no_of_errors++;
cerr << "error:" << s << '\n';
return 1;
}
istream* input;
int main(int argc, char* argv[])
{
map<string,double>table;
switch (argc) {
case 1:
input = &cin;
break;
case 2:
input = new istringstream(argv[1]);
break;
default:
error ("too many arguments");
return 1;
}
table["pi"] = 3.1415926535897932385;
table["e"] = 2.7182818284590452354;
while (*input){
get_token();
if (curr_tok == END)break;
if (curr_tok == PRINT)continue;
cout << expr(false) << '\n';
}
if (input != &cin)delete input;
return no_of_errors;
}
这是在书上抄下来的c++代码,你可以编译然后在终端运行一下.然而我想给它加个ui,那就用qt吧!下面是用设计师绘制的界面
问题来了.
1.原来的程序的输入用的是cin,但是qt的控件QTextEdit似乎是用text()函数获取输入的字符串,这里要如何转换呢.
2.原输出是直接cout << expr(flase) <<endl,qt的控件QTextBrowser是用textBrowser->setText(QString::number(result,'f',2));这样的,如何转换呢