#include #include #include struct element { string name, symbol; double weight; }; const int max_table_size = 110; struct periodic_table { element table[max_table_size]; int num_elements; }; void make(periodic_table & t) { t.num_elements=0; } element make(string s, string n, double w) { element r; r.symbol=s; r.name=n; r.weight=w; return r; } element find_symbol(periodic_table t, string s) { for (int i=0; i> sy >> nm >> wt; if (efile.fail()) break; t.table[i]=make(sy, nm, wt); t.num_elements=i; } efile.close(); } struct inputthing { string formula; int pos; }; void read(inputthing & x, string prompt="") { cout << prompt; cin >> x.formula; x.pos=0; } string combine(char a, char b=0) { string s=""; s+=a; if (b!=0) s+=b; return s; } char nextchar(inputthing & w) { if (w.pos>=w.formula.length()) { w.pos+=1; return '*'; } char c=w.formula[w.pos]; w.pos+=1; return c; } void putcharback(inputthing & w) { w.pos-=1; } struct item { string str; int num; char which; /* 'S' means string, 'N' means number */ }; item makeitem(char w) { item r; r.which=w; return r; } item makeitem(string s) { item r; r.str=s; r.which='S'; return r; } item makeitem(int n) { item r; r.num=n; r.which='N'; return r; } item nextsymbol(inputthing & x) { char c1=nextchar(x); if (c1=='*') return makeitem('*'); else if (c1=='(') return makeitem('('); else if (c1==')') return makeitem(')'); else if (c1>='A' && c1<='Z') { char c2=nextchar(x); if (c2>='a' && c2<='z') return makeitem(combine(c1, c2)); putcharback(x); return makeitem(combine(c1)); } else if (c1>='0' && c1<='9') { int value = c1 - '0'; char c2=nextchar(x); while (c2>='0' && c2<='9') { value = value * 10 + c2 - '0'; c2=nextchar(x); } putcharback(x); return makeitem(value); } else return makeitem('?'); } double molecular_weight(periodic_table PT, inputthing & reader) { double total=0.0, last=0.0, memory=0.0; while (true) { item it = nextsymbol(reader); if (it.which=='*') break; else if (it.which=='(') { memory=total; total=0; } else if (it.which==')') { last=total; total+=memory; } else if (it.which=='S') { element e = find_symbol(PT, it.str); last=e.weight; total+=last; } else if (it.which=='N') { total+=last*(it.num-1); } else if (it.which=='?') { cerr << "It doesn't make sense\n"; total=-999999; break; } } return total; } void main() { periodic_table PT; make(PT); read(PT); inputthing reader; read(reader, "formula: "); double total=molecular_weight(PT, reader); cout << "molecular weight = " << total << "\n"; }