Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created November 18, 2025 13:43
Show Gist options
  • Select an option

  • Save juanfal/0e2a76c9e166056dc3a4e7d90476e2b1 to your computer and use it in GitHub Desktop.

Select an option

Save juanfal/0e2a76c9e166056dc3a4e7d90476e2b1 to your computer and use it in GitHub Desktop.
Molecules
// t12e13.chemicalmolecules.cpp
// juanfc 2025-11-18
// Chemical compounds are made of many identical molecules. A molecule consists
// of a sequence (an array) of elements. These elements are atoms (e.g., Fe, H,
// Ni) repeated in the molecule. An integer indicates how many times that atom
// appears in the molecule. Each element (|TElement|) can therefore be a
// structure storing a string representing the atom (the letter Fe, H, etc.)
// together with its frequency (an integer in the range 1–9). A molecule
// (TMolecule) is then an open array of TElement of these .
// Write a function |TMolecule string2Molec(string s);| that parses the input
// string and returns a |TMolecule| structure.
// Write also a procedure to print them: |void printMol(TMolecule);| in the
// classic way. So |printMol((TMolecule){{"Na", 1}, { "O", 1}, {"H", 1}})| would
// print: |NaOH|
#include <iostream>
#include <array>
using namespace std;
const int N = 100;
struct TElement {
string elem;
int n;
};
typedef array<TElement,N> TMolecule;
struct TMulMolec {
TMolecule m;
int n;
};
typedef array<TMulMolec,N> TMixMolec;
struct TReaction {
TMixMolec reactants;
TMixMolec products;
};
int main()
{
TMolecule string2Molec(string s);
void print(TMolecule);
TMolecule chloricAcid = string2Molec("HCl");
TMolecule sodiumHidroxide = string2Molec("NaOH");
print(chloricAcid);
print(sodiumHidroxide);
return 0;
}
TMolecule string2Molec(string s)
{
TMolecule r;
int last = 0;
TElement e;
for (int i = 0; i < s.size(); ++i) {
if (s[i] >= 'A' and s[i] <= 'Z') {
// new element, add the previous if any
if (e.elem != "") {
r[last++] = e;
}
e.elem = s[i];
e.n = 1;
} else if (s[i] >= 'a' and s[i] <= 'z') {
e.elem += s[i];
} else if (s[i] >= '0' and s[i] <= '9') {
e.n = s[i] - '0'; // only one digit
}
}
if (e.elem != "") {
r[last++] = e;
}
return r;
}
void print(TMolecule m)
{
int i = 0;
while (m[i].elem != "") {
cout << m[i].elem;
if (m[i].n > 1)
cout << m[i].n;
++i;
}
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment