/* The plan: A. Read the entire file into an array of structs B. Given a symbol, be able to search the array to find the corresponding element's data C. Split a chemical formula such as Na2SO4 into its component parts: symbol Na, multiplier 2, symbol S, symbol O, multiplier 4 D. Combine B and C to calculate molecular weights E. Print results nicely in a text file. */ #include #include #include using namespace std; struct element { int atno; string symbol; string name; double atwt; }; // The next function implements part A int read_file(element A[], int arr_size) // returns actual number read. { ifstream f("/home/www/class/een118/atwt.txt"); if (f.fail()) { cout << "Failed to open atwt.txt file\n"; exit(1); } int i = 1; while (i> sym >> name >> wt; if (f.fail()) break; A[i].atno = i; A[i].symbol = sym; A[i].name = name; A[i].atwt = wt; i += 1; } if (! f.fail()) cout << "Warning!!!! too many elements\n"; f.close(); return i - 1; } // The next function implements part B int lookup(string sym, element T[], int num) // returns position in array // or -1 for "not found" { for (int i=1; i<=num; i+=1) { if (T[i].symbol == sym) return i; } cout << sym << " not found\n"; return -1; } int main() { element table[110]; int num_els = read_file(table, 110); while (true) // this loop tests parts A and B. { string s; cin >> s; int pos = lookup(s, table, num_els); if (pos>0) { element e = table[pos]; cout << "name = " << e.name << ", number = " << e.atno << "\n"; } } }