#include #include #include using namespace std; struct element { string symbol, name; int at_no; double at_wt; }; void print(element e) { cout << e.at_no << ": " << e.symbol << ", " << e.name << ", at wt = " << e.at_wt << "\n"; } const int max_num_els = 110; element table[max_num_els]; int num_els = 0; void read_table(ifstream & f) { while (num_els < max_num_els) { f >> table[num_els+1].symbol >> table[num_els+1].name >> table[num_els+1].at_wt; table[num_els+1].at_no = num_els + 1; if (f.fail()) return; num_els += 1; } } int find(string sy) { for (int i = 1; i <= num_els; i += 1) if (table[i].symbol == sy) return i; return 0; } int convert(string s) { int sofar = 0; for (int i = 0; i < s.length(); i += 1) sofar = sofar * 10 + s[i] - '0'; return sofar; } bool is_number(string s) { for (int i = 0; i < s.length(); i += 1) if ( ! (s[i] >= '0' && s[i] <= '9')) return false; return true; } double read_formula() { double total = 0.0, prev_wt = 0.0; while (true) { string sy; cin >> sy; if (sy == ".") return total; if (is_number(sy)) { int N = convert(sy); total += (N - 1) * prev_wt; cout << " correcting " << prev_wt << " to " << N * prev_wt << "\n"; } else { int epos = find(sy); if (epos < 1) { cout << "element " << sy << " not known\n"; while (true) { cin >> sy; if (sy == ".") break; } return 0; } print(table[epos]); prev_wt = table[epos].at_wt; total += prev_wt; } } } int main() { ifstream file("table.txt"); if (file.fail()) { cout << "Can't read table file\n"; exit(1); } read_table(file); file.close(); cout << num_els << " elements read\n"; // print(table[92]); // print(table[104]); // left over from an earlier test // print(table[1]); // print(table[8]); while (true) { cout << "Enter formula: "; double mol_wt = read_formula(); cout << "molecular weight = " << mol_wt << "\n"; } }