2.4 Generating a SMILES from a Molecule

To produce a SMILES string from a molecule, use OEChem's OECreateCanSmiString  OECreateCanSmiString converts the given OEMolBase into a canonical SMILES string and returns the result in a C++ string, as defined by C++'s Standard Template Library (STL). Note the slight asymmetry: Many OEChem functions take const char * as incoming arguments, but return STL strings as results. This usage makes the ownership of the strings explicit. This should never be a difficulty as C and C++ strings may be easily inter-converted using standard STL functions.

 1 #include "openeye.h"
 2 #include "oechem.h"
 3 #include <iostream>
 4 #include <string>
 5
 6 using namespace OEChem;
 7 using namespace std;
 8
 9 int main()
10 {
11   string str;
12   OEGraphMol mol;
13
14   if (OEParseSmiles(mol,"c1ccccc1"))
15   {
16     OEAssignAromaticFlags(mol);
17     OECreateCanSmiString(str,mol);
18     cout << "Canonical SMILES is " << str << endl;
19   }
20   else cerr << "SMILES string was invalid!" << endl;
21   return 0;
22 }

Listing:2.7 Generating a SMILES from a molecule

The following slightly more complicated example reads SMILES from cin and writes the corresponding canonical SMILES to cout.

 1 #include "openeye.h"
 2 #include "oechem.h"
 3 #include <iostream>
 4 #include <string>
 5
 6 using namespace OEChem;
 7 using namespace std;
 8
 9 int main()
10 {
11   char buffer[1024];
12   string str;
13   OEGraphMol mol;
14
15   while (cin.getline(buffer,1024))
16   {
17     mol.Clear();
18     if (OEParseSmiles(mol,buffer))
19     {
20       OEAssignAromaticFlags(mol);
21       OECreateCanSmiString(str,mol);
22       cout << str << endl;
23     }
24     else cerr << buffer << " is an invalid SMILES!" << endl;
25   }
26   return 0;
27 }

Listing:2.8 Reading and writing SMILES

Notice that this example makes use of the OEMolBase::Clear function to reuse the molecule. The behavior of OEParseSmiles is to add the given SMILES to the current molecule. If the line mol.Clear() were removed from the program, the output would contain longer and longer SMILES containing disconnected fragments.

The above program could also have been written to construct and destruct molecules and strings:

 1 #include "openeye.h"
 2 #include "oechem.h"
 3 #include <iostream>
 4 #include <string>
 5
 6 using namespace OEChem;
 7 using namespace std;
 8
 9 int main()
10 {
11   char buffer[1024];
12
13   while (cin.getline(buffer,1024))
14   {
15     OEGraphMol mol;
16     if (OEParseSmiles(mol,buffer))
17     {
18       string str;
19       OEAssignAromaticFlags(mol);
20       OECreateCanSmiString(str,mol);
21       cout << str << endl;
22     }
23     else cerr << buffer << " is an invalid SMILES!" << endl;
24   }
25   return 0;
26 }

Listing:2.9 Constructing new molecules for each SMILES