//// Calculator, add "{ }" and '!' operators// //#include"../../std_lib_facilities.h"//------------------------------------------------------------------------------classToken{public:char kind;// what kind of tokendouble value;// for numbers: a value Token(char ch)// make a Token from a char:kind(ch),value(0){}Token(char ch,double val)// make a Token from a char and a double:kind(ch),value(val){}};classToken_stream{public:Token_stream();
Token get();// get a tokenvoidputback(Token t);// put back a tokenprivate:bool full{false};// is buffer full?
Token buffer;// a buffer for token by putback()};//------------------------------------------------------------------------------// The constructor just sets full to indicate that the buffer is empty:Token_stream::Token_stream():full(false),buffer(0)// no Token in buffer{}
Token Token_stream::get()// read a token from cin{if(full){
full =false;return buffer;}char ch;
cin >> ch;// note that >> skips whitespace (space, newline, tab, etc.)switch(ch){case'=':// for "print"case'x':// for "quit"case'(':case')':case'{':case'}':case'+':case'-':case'*':case'/':case'!':return Token{ ch };// let each character represent itselfcase'.':case'0':case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':{
cin.putback(ch);// put digit back into the input streamdouble val;
cin >> val;// read a floating-point numberreturnToken('8', val);// let '8' represent "a number"}default:error("Bad token");}}// The putback() member function puts its argument back into the Token_stream's buffer:voidToken_stream::putback(Token t){if(full)error("putback() into a full buffer.");
buffer = t;
full =true;}//------------------------------------------------------------------------------
Token_stream ts;// provides get() and putback()//------------------------------------------------------------------------------doubleexpression();// read and evaluate a Expression//------------------------------------------------------------------------------doubleprimary()// read and evaluate a Primary{
Token t = ts.get();switch(t.kind){case'(':// handle '(' expression ')'{double d =expression();
t = ts.get();if(t.kind !=')')error("')' expected");return d;}case'{':// handle '{' expression '}'{double d =expression();
t = ts.get();if(t.kind !='}')error("'}' expected");return d;}case'8':// we use '8' to represent a number{
Token tt = ts.get();if(tt.kind =='!'){int x = narrow_cast<int>(t.value);//defined in std_lib_facilitiesif(x ==0)return1;for(int i = x -1; i >0; i--)
x *= i;return x;}else
ts.putback(tt);return t.value;// return the number's value}case'x':case'=':
ts.putback(t);return t.value;default:error("primary expected");}}//------------------------------------------------------------------------------doubleterm(){double left =primary();
Token t = ts.get();// get the next tokenwhile(true){switch(t.kind){case'*':
left *=primary();
t = ts.get();break;case'/':{double d =primary();if(d ==0)error("divide by zero");
left /= d;
t = ts.get();break;}default:
ts.putback(t);return left;}}}//------------------------------------------------------------------------------doubleexpression(){double left =term();// read and evaluate a Term
Token t = ts.get();// get the next tokenwhile(true){switch(t.kind){case'+':
left +=term();// evaluate Term and add
t = ts.get();break;case'-':
left -=term();// evaluate Term and subtract
t = ts.get();break;default:
ts.putback(t);return left;// finally: no more + or -: return the answer}}}//------------------------------------------------------------------------------intmain()try{
cout <<"Welcome to our simple calculator.\n";
cout <<"Please enter expressions using floating-point numbers.\n";
cout <<"You can use \" + - * / ! \" operators, '=' to output result, and 'x' to quit.\n";
Token t{0};double val{0};while(cin){
t = ts.get();if(t.kind =='x')break;elseif(t.kind =='=')
cout <<"= "<< val <<'\n';else
ts.putback(t);
val =expression();}keep_window_open("~0");return0;}catch(exception& e){
cerr << e.what()<< endl;keep_window_open("~1");return1;}catch(...){
cerr <<"exception \n";keep_window_open("~2");return2;}
6.6
#include"../../std_lib_facilities.h"
vector<string>conj{"and","or","but"};
vector<string>article{"a","an","the"};
vector<string>noun{"birds","fish","C++"};
vector<string>verb{"rules","fly","swim"};boolsearch_word(string word, vector<string>words){for(string x : words)if(word == x)returntrue;returnfalse;}boolsentence(){
string word;
string sents;bool flag =false;// 标识是否在单词集合中
cin >> word;if(!cin)error("can't read a word.");//首先判断是否是冠词
flag =search_word(word, article);if(flag){
cin >> word;if(!cin)error("can't read a word.");}//然后判断是否为名词
flag =search_word(word, noun);if(flag){
cin >> word;if(!cin)error("can't read a word.");}elsereturnfalse;//如果不是名词,那么根据我们的简单语法,这不是一个句子//之后判断是否为动词
flag =search_word(word, verb);char dot;//用于读入可能的dotif(flag){
cin >> dot;//读入可能的句号if(!cin)error("can't read a word.");}elsereturnfalse;//如果不是动词,那么根据我们的简单语法,这不是一个句子//最后判断是否为结束的句号或者连词if(dot =='.')returntrue;else{
cin.putback(dot);
cin >> word;if(!cin)error("can't read a word.");}
flag =search_word(word, conj);if(flag)returnsentence();//连词后要接一个新的句子,那么问题转化为判断新的句子是否符合语法了。elsereturnfalse;}//------------------------------------------------------------------------------intmain()try{
cout <<"Enter a English sentence, the program will output \"OK\" or \"not OK\".\n";
cout <<"Your input sentences must have none, verbs and a '.' with two space between '.',";
cout <<"article and conjunction is optional.\n";
cout <<"enter ~ to quit\n";char ch;bool is_right{false};while(cin){
cin >> ch;if(ch =='~')break;else
cin.putback(ch);
is_right =sentence();
cout <<(is_right ?"OK":"not OK")<<'\n';}keep_window_open("~0");return0;}catch(exception& e){
cerr << e.what()<< endl;keep_window_open("~1");return1;}catch(...){
cerr <<"exception \n";keep_window_open("~2");return2;}
6.7
//// Calculator, deal with logic expression// ! ~ & | ^//#include"../../std_lib_facilities.h"//------------------------------------------------------------------------------classToken{public:char kind;// what kind of tokenint value;// for numbers: a value Token(char ch)// make a Token from a char:kind(ch),value(0){}Token(char ch,int val)// make a Token from a char and a int:kind(ch),value(val){}};classToken_stream{public:Token_stream();
Token get();// get a tokenvoidputback(Token t);// put back a tokenprivate:bool full{false};// is buffer full?
Token buffer;// a buffer for token by putback()};//------------------------------------------------------------------------------// The constructor just sets full to indicate that the buffer is empty:Token_stream::Token_stream():full(false),buffer(0)// no Token in buffer{}
Token Token_stream::get()// read a token from cin{if(full){
full =false;return buffer;}char ch;
cin >> ch;// note that >> skips whitespace (space, newline, tab, etc.)switch(ch){case'=':// for "print"case'q':// for "quit"case'(':case')':case'{':case'}':case'~':case'!':case'^':case'&':case'|':return Token{ ch };// let each character represent itselfcase'0':case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':{
cin.putback(ch);// put digit back into the input streamint val;
cin >> val;// read a floating-point numberreturnToken('8', val);// let '8' represent "a number"}default:error("Bad token");}}// The putback() member function puts its argument back into the Token_stream's buffer:voidToken_stream::putback(Token t){if(full)error("putback() into a full buffer.");
buffer = t;
full =true;}//------------------------------------------------------------------------------
Token_stream ts;// provides get() and putback()//------------------------------------------------------------------------------intexpression();// read and evaluate a Expression//------------------------------------------------------------------------------intprimary()// read and evaluate a Primary{
Token t = ts.get();switch(t.kind){case'(':// handle '(' expression ')'{int d =expression();
t = ts.get();if(t.kind !=')')error("')' expected");return d;}case'{':// handle '{' expression '}'{int d =expression();
t = ts.get();if(t.kind !='}')error("'}' expected");return d;}case'8':// we use '8' to represent a number{
Token tt = ts.get();if(tt.kind =='!')//处理阶乘,这里的!符号是后置的{int x = narrow_cast<int>(t.value);//defined in std_lib_facilitiesif(x ==0)return1;for(int i = x -1; i >0; i--)
x *= i;return x;}else
ts.putback(tt);return t.value;// return the number's value}case'!':{int right =primary();return!right;}case'~':{int right =primary();return~right;}case'q':case'=':
ts.putback(t);return t.value;default:error("primary expected");}}//------------------------------------------------------------------------------intterm_and(){int left =primary();
Token t = ts.get();// get the next tokenwhile(true){switch(t.kind){case'&':
left &=primary();
t = ts.get();break;default:
ts.putback(t);return left;}}}//------------------------------------------------------------------------------intterm_xor(){int left =term_and();
Token t = ts.get();// get the next tokenwhile(true){switch(t.kind){case'^':
left ^=term_and();
t = ts.get();break;default:
ts.putback(t);return left;}}}//------------------------------------------------------------------------------intexpression(){int left =term_xor();// read and evaluate a Term
Token t = ts.get();// get the next tokenwhile(true){switch(t.kind){case'|':
left |=term_xor();// evaluate Term and add
t = ts.get();break;default:
ts.putback(t);return left;// finally: no more + or -: return the answer}}}//------------------------------------------------------------------------------intmain()try{
cout <<"Welcome to our simple logic calculator.\n";
cout <<"Please enter logic expressions using integer numbers.\n";
cout <<"You can use \" ! ~ & ^ | \" operators, '=' to output result, and 'q' to quit.\n";
Token t{0};int val{0};while(cin){
t = ts.get();if(t.kind =='q')break;elseif(t.kind =='=')
cout <<"= "<< val <<'\n';else
ts.putback(t);
val =expression();}keep_window_open("~0");return0;}catch(exception& e){
cerr << e.what()<< endl;keep_window_open("~1");return1;}catch(...){
cerr <<"exception \n";keep_window_open("~2");return2;}
6.10
#include"../../std_lib_facilities.h"intfactorial(int n){if(n <0)error("N factorial, N can't lower than zero");int fac =1;while(n >1)
fac *= n--;return fac;}intpermutations(int a,int b){// P(a, b)if(a < b || a <1|| b <1)error("bad permutation sizes");returnfactorial(a)/factorial(a - b);}intcombinations(int a,int b){returnpermutations(a, b)/factorial(b);}intmain()try{
cout <<"This calculator gives two functions of calculating permutation and combination\n\n";
cout <<"You should choose the function you want, like C or P"<< endl;
cout <<"enter a size of set(a) and a size of subset(b), a must bigger than b"<< endl;
cout <<"For example: C 7 3"<< endl;
cout <<"The calculator will calculate combination of C(7,3) and output 35 as result\n";
cout <<"Enter 'q' or \"quit\" to quit\n";
string choice;while(true){
cin >> choice;if(choice[0]=='P'|| choice[0]=='p'||!_stricmp(choice.c_str(),"permutation")){int a{0}, b{0};
cin >> a >> b;int p =permutations(a, b);
cout <<"P("<< a <<','<< b <<") = "<< p << endl;}elseif(choice[0]=='C'|| choice[0]=='c'||!_stricmp(choice.c_str(),"combination")){int a{0}, b{0};
cin >> a >> b;int c =combinations(a, b);
cout <<"C("<< a <<','<< b <<") = "<< c << endl;}elseif(choice[0]=='q'||!_stricmp(choice.c_str(),"quit"))break;else
cout <<"Please enter right function choice."<< endl;
cout <<"Try again!"<< endl;}
cout <<"Bye!\n";return0;}catch(runtime_error& e){
cerr << e.what()<< endl;return1;}catch(...){
cerr <<"exception \n";return2;}