As the title indicates, I'm building a simple program as an exercise in GUI programming with the API, and for some extra points in chem class, which can calculate the molar mass of a chemical substance.
Eg, you input something like NaCl, and you'd get: M(NaCl) = 58,4527.
Anyway, the hard part is mapping each substance to its respective mass. First I thought about just creating two arrays - one double and one char. However, that'd mean extra, extra bloated code due to the annoyance of strcpying into the buffer when hard-coding the masses.
So I thought I'd just use strings(Which is why this is in the C++ board), and a struct with the mass and name of the substance(Not name, but you know.. Na and Cl and He etc..) and I'd initialize the struct as such:
Code:
struct molmass MolMass[] =
{
{ 1.00794, "H" },
{ 4.0026, "He" },
{ 6.941, "Li" },
{ 9.01218, "Be" },
{ 10.811, "B" },
{ 12.011, "C" },
// ....
... and so on.
However, then I can't help but think that coding up an algorithm that would parse the the text input by the user and then find the mass in the struct would be somewhat annoying, because of different substances with similar names, such as "CO2", which is Carbondioxide, and then "Co" which is cobalt.
So I had another idea: Just a switch statement, for every letter in the alphabet, then nested if and switch statements to determine if the substance has a second letter in its name, and if so, add the respective mass to the sum of the result.
Basically, what I'm asking is - Can someone come up with a better idea? Those ideas are all doable, but they all mean a LOT of bloated code which would be hard to maintain, to be honest, but IMO, the switch statement sounds best right now.
All hints and suggestions will be greatly appreciated.