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 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. The should never be a difficulty as C and C++ strings may be easily inter-converted using standard STL functions.

#include "oechem.h"
#include <iostream>
#include <string>

using namespace OEChem;
using namespace std;

int main()
{
  string str;
  OEMol mol;

  if (OEParseSmiles(mol,"c1ccccc1"))
  {
    OEAssignAromaticFlags(mol);
    OECreateCanSmiString(str,mol);
    cout << "Canonical SMILES is " << str << endl;
  }
  else cerr << "SMILES string was invalid!" << endl;
  return 0;
}

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

#include "oechem.h"
#include <iostream>
#include <string>

using namespace OEChem;
using namespace std;

int main()
{
  char buffer[1024];
  string str;
  OEMol mol;

  while (cin.getline(buffer,1024))
  {
    mol.Clear();
    if (OEParseSmiles(mol,buffer))
    {
      OEAssignAromaticFlags(mol);
      OECreateCanSmiString(str,mol);
      cout << str << endl;
    }
    else cerr << buffer << " is an invalid SMILES!" << endl;
  }
  return 0;
}

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:

#include "oechem.h"
#include <iostream>
#include <string>

using namespace OEChem;
using namespace std;

int main()
{
  char buffer[1024];

  while (cin.getline(buffer,1024))
  {
    OEMol mol;
    if (OEParseSmiles(mol,buffer))
    {
      string str;
      OEAssignAromaticFlags(mol);
      OECreateCanSmiString(str,mol);
      cout << str << endl;
    }
    else cerr << buffer << " is an invalid SMILES!" << endl;
  }
  return 0;
}