#include #include #include struct element { string name, symbol; double weight; }; element table[105]; element make(string s, string n, double w) { element r; r.symbol=s; r.name=n; r.weight=w; return r; } element find_symbol(string s) { for (int i=1; i<=104; i+=1) { if (table[i].symbol == s) { return table[i]; } } return make("?", "!!!error!!!", -999999); } void print(element e) { cout << e.name << " (" << e.symbol << ") w=" << e.weight << "\n"; } void read() { ifstream efile("elements.txt"); if (efile.fail()) { cerr << "Can't open 'elements.txt'\n"; exit(1); } for (int i=1; i<=104; i+=1) { string sy, nm; double wt; efile >> sy >> nm >> wt; if (efile.fail()) break; table[i]=make(sy, nm, wt); } 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('?'); } void main() { read(); inputthing reader; read(reader, "formula: "); 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(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; } } cout << "molecular weight = " << total << "\n"; }