#include #include #include using namespace std; bool isnum(string s) { const int len = s.length(); int i = 0; while (i < len) { char c = s[i]; if (c < '0' || c > '9') return false; i = i + 1; } return true; } int numericval(string s) { const int len = s.length(); int total = 0; for (int i = 0; i < len; i += 1) { char c = s[i]; int v = (int)c - (int)'0'; total = total * 10 + v; } return total; } struct element { int atno; string symbol, name; double atwt; }; void print(element e) { cout << e.atno << ", "; cout << e.symbol << ", "; cout << e.name << ", "; cout << e.atwt << "\n"; } struct pertab // short for periodic table { static const int arrsize = 120; element table[arrsize]; int numels; }; void empty(pertab & PT) { PT.numels = 0; } void read_elements(pertab & PT) { ifstream fin; fin.open("/home/www/class/een118/a3010b.txt"); if (fin.fail()) { cout << "Can't read file\n"; exit(1); } PT.table[0].atno = 0; PT.table[0].symbol = "?"; PT.table[0].name = "ERROR!!!!!!!!!"; PT.table[0].atwt = -999999999999999.9; int atno = 0; while (atno < PT.arrsize - 1) { string symbol, name; double atwt; fin >> symbol >> name >> atwt; if (fin.fail()) break; atno = atno + 1; PT.table[atno].atno = atno; PT.table[atno].symbol = symbol; PT.table[atno].name = name; PT.table[atno].atwt = atwt; } cout << atno << " Elements successfully read\n"; fin.close(); PT.numels = atno; } element find_elem(string sym, const pertab & PT) { int i = 1; while (i <= PT.numels) { if (sym == PT.table[i].symbol) return PT.table[i]; i = i + 1; } return PT.table[0]; } // 0 means not found int main() { pertab PT; empty(PT); read_elements(PT); double molwt = 0.0; cout << "Enter a formula: "; bool ok = true; double lastatwt = 0.0; while (true) { string s; cin >> s; if (s == ".") break; if (isnum(s)) { int n = numericval(s); molwt += (n - 1) * lastatwt; cout << "Revised " << lastatwt << " to " << n * lastatwt << "\n"; continue; } element e = find_elem(s, PT); if (e.atno == 0) { cout << s << ": No such element\n"; ok = false; continue; } lastatwt = e.atwt; print(e); molwt = molwt + e.atwt; } if (ok) cout << "Molecular weight = " << molwt << "\n"; else cout << "There was an error in the input\n"; }