#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)) // what goes here? else if (isdigit(c)) // and what goes here? else { cout << "Improper character " << c << " in input\n"; return "*"; } int main() { string symbols[120]; string names[120]; double atwts[120]; string filename = "/home/www/class/een118/a3010b.txt"; ifstream fin; fin.open(filename); if (fin.fail()) { cout << "Couldn't open " << filename << "\n"; exit(1); } 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(); 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 = -1; for (int i = 0; i < num; i += 1) if (symbols[i] == sym) { pos = i; break; } 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"; }