/* The plan 0. use official C++ libraries the official way 1. read the file into an array 2. be able to search the table 3. read chemical formula from user 4. work out total weight */ #include #include #include using namespace std; struct element { string symbol, name; int atnumber; double atweight; }; // defined "element" as a new type of variable/constant void print(element X) { cout << X.symbol << "(\"" << X.name << "\", "; cout << X.atnumber << ", " << X.atweight << ")\n"; } void read(element & e, ifstream & f) { f >> e.symbol >> e.name >> e.atweight; } element search(string sy, element tab[], int max) /* given symbol for an element, and whole periodic table, and number of elements in the table, search table for match, and return the element object */ { for (int i = 1; i <= max; i += 1) if (tab[i].symbol == sy) return tab[i]; // if user mistypes symbol got to return something easily detected tab[0].atnumber = 0; return tab[0]; } int main() { ifstream f; // f.open("http://rabbit.eng.miami.edu/class/een118/atwt.txt"); // Can't open a URL, files only string filename = "/home/www/class/een118/atwt.txt"; f.open(filename.c_str()); // .c_str() given old C equivalent of C++ string if (f.fail()) { cout << "Can't open file '" << filename << "'\n"; return 0; } element ptable[150]; // flexible for future growth int numels; // read the table for (int atno = 1; atno < 150; atno += 1) { element e; read(e, f); if (f.fail()) { numels = atno - 1; break; } e.atnumber = atno; ptable[atno] = e; } f.close(); // just while testing, verify it worked cout << "Finished reading " << numels << " elements\n"; for (int i = 1; i <= numels; i += 1) print(ptable[i]); // test the search function while (true) { cout << "type a symbol. "; string s; cin >> s; element x = search(s, ptable, numels); if (x.atnumber == 0) cout << "no such thing\n"; // special fake element to signal error else print(x); } }