#include "library.h" /* The user can type any molecular formula, such as NaCl H2O Ca(OH)2 CH3(CH2)4CH3 and so on, no matter how complicated, even with nested brackets, and the program calculates the molecular weight. */ struct element { string symbol, name; double atwt; }; int lookup(string atom, element PT[], int max) { for (int i=1; i<=max; i+=1) { if (PT[i].symbol == atom) return i; } return -1; } int read_table(element A[]) { ifstream fin("atwt.txt"); if (fin.fail()) { cout << "No file\n"; return 0; } int count = 0; while (true) { fin >> A[count+1].symbol >> A[count+1].name >> A[count+1].atwt; if (fin.fail()) break; count += 1; } fin.close(); return count; } string read_atom() { string symbol; char c, d; c = cin.get(); if (!isupper(c)) { if (c == '\n') return "*end*"; cout << "Not a capital\n"; return ""; } d = cin.get(); if (islower(d)) { symbol = c; symbol = symbol + d; } else { symbol = c; cin.unget(); } return symbol; } double read_and_calculate(element ptable[], int number) { double total = 0.0, lastadded = 0.0; while (true) { char nextc = cin.get(); cin.unget(); if (nextc=='\n' || nextc==')') { cin.get(); return total; } else if (nextc=='(') { cin.get(); double forwt = read_and_calculate(ptable, number); total += forwt; lastadded = forwt; } else if (isalpha(nextc)) { string atom = read_atom(); int an = lookup(atom, ptable, number); if (an<=0) cout << "'" << atom << "': unknown symbol\n"; else { cout << atom << ", " << ptable[an].name << ": "; cout << "at.no. = " << an << ", "; cout << "at.wt. = " << ptable[an].atwt << "\n"; total += ptable[an].atwt; lastadded = ptable[an].atwt; } } else if (isdigit(nextc)) { int value = 0; while (true) { char c = cin.get(); if (isdigit(c)) { value = value * 10 + c - '0'; } else { cin.unget(); break; } } cout << " last unit x " << value << ", adding " << (value-1)*lastadded << "\n"; total += (value-1)*lastadded; } else cout << "Error symbol\n"; } } void main() { element ptable[120]; int number = read_table(ptable); cout << "read " << number << " elements\n\n"; while (true) { cout << "Formula: "; double molwt = read_and_calculate(ptable, number); cout << "\nMolecular weight is " << molwt << "\n\n"; } }