Today is Day 3 of working on what is essentially my CLI search engine for the periodic table written in C++ to both learn the language and build a solution for a slight frustration I had.
I remember being in class a few months ago and having a science test for our chemistry unit. One of the ending sections was an incomplete table of element attributes with spaces you'd have to fill in to come up with the element and its details. At that moment, scratching my head over what specific element would have an atomic mass of X, I thought, even though it probably wouldn't have been allowed, some kind of "sorter" that would filter through the periodic table to get me the element and its attributes would be really convenient.
That takes me to here. I'm using C++ as the language of choice because I've dabbled in it before and wanted to strengthen my skills.
We begin by dissecting the program by design. It will need:
- A periodic table of its own (in the form of a .csv file).
- A "search bar" (user input).
- Instructions on what output to print out based on input.
- "Case-insensitive querying" (like the way we technically misspell the majority of our Google searches).
I began by #include-ing the usual libraries like fstream,
sstream, algorithm, and vector, which would allow me to manage the data and accessing/presenting the elements.
Then I created a struct for attributes:
`struct Element
{
int atomicNum;
string symbol;
string name;
float atomicMass;
string category;
Element(int num, string sym, string element, float mass, string cat)
: atomicNum(num), symbol(sym), name(element), atomicMass(mass), category(cat) {}
};`
A periodic table for our little Google Search-in-the-making was required so I created a short 'elements.csv' file, too:
1,H,Hydrogen,1.008,Non-metals
2,He,Helium,4.0026,Noble Gases
8,O,Oxygen,15.999,Reactive Non-Metals
3,Li,Lithium,6.94,Alkali Metals
I needed to learn some of these concepts, like making the sorter case-insensitive so it can take lower-case input, quickly so I could implement them in the program and used clear comments to tell myself what almost each line did:
string toLower(const string &s)
{
string result = s;
transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
}
...and...
` // Skip empty lines
stringstream ss(line);
string field;
// Check if line is empty
int atomicNum;
string symbol, name, category;
float atomicMass;
// Read each field
getline(ss, field, ',');
atomicNum = stoi(field);
// Read symbol and name
getline(ss, symbol, ',');
getline(ss, name, ',');
// Read atomic mass
getline(ss, field, ',');
atomicMass = stof(field);
// Read category
getline(ss, category, ',');
elements.emplace_back(atomicNum, symbol, name, atomicMass, category);`
That's the majority of what I've done in these past two days so far for the program. Feel free to check out the full project on Github. Thanks for reading!
Stay alert for the next devlog and consider giving me a follow?
Top comments (0)