#include #include #include #include using namespace std; bool isanumber(string s) { for (int i = 0; i < s.length(); i += 1) if (! isdigit(s[i])) return false; return true; } int stringtoint(string s) { int value = 0; for (int i = 0; i < s.length(); i += 1) value = value * 10 + digittoint(s[i]); return value; } int sympos = 0; string input; string getnextsymbol() { if (sympos >= input.length()) return "*"; char c = input[sympos]; sympos += 1; if (isupper(c)) { string sym = ""; sym += c; char nextc = input[sympos]; if (islower(nextc)) { sym += nextc; sympos += 1; } return sym; } else if (isdigit(c)) { string num = ""; while (isdigit(c)) { num += c; c = input[sympos]; sympos += 1; } sympos -= 1; return num; } else { cout << "Improper character " << c << " in input\n"; return "*"; } } ifstream openfile(string filename) { ifstream fin; fin.open(filename); if (fin.fail()) { cout << "Couldn't open " << filename << "\n"; exit(1); } return fin; } int readdata(ifstream & fin, string symbols[], string names[], double atwts[]) { symbols[0] = "Xx"; names[0] = "Does not exist"; atwts[0] = 0.0; int num = 1; while (num < 120) { fin >> symbols[num] >> names[num] >> atwts[num]; if (fin.fail()) break; num += 1; } fin.close(); return num; } int find(string sym, string symbols[], int num) { int pos = -1; for (int i = 0; i < num; i += 1) if (symbols[i] == sym) { pos = i; break; } return pos; } int main() { string symbols[120]; string names[120]; double atwts[120]; ifstream fin = openfile("/home/www/class/een118/a3010b.txt"); int num = readdata(fin, symbols, names, atwts); bool errors = false; double molwt = 0.0; double prevatwt = 0.0; cout << "Enter the formula: "; cin >> input; while (true) { string sym = getnextsymbol(); if (sym == "*") break; if (isanumber(sym)) { int value = stringtoint(sym); molwt += (value - 1) * prevatwt; continue; } int pos = find(sym, symbols, num); if (pos == -1) { cout << "symbol " << sym << " Not found\n"; errors = true; break; } prevatwt = atwts[pos]; cout << "Adding " << names[pos] << ", at " << atwts[pos] << "\n"; molwt += atwts[pos]; } if (! errors) cout << "Total molecular weight = " << molwt << "\n"; }