mercredi 1 février 2017

How to use std::string effectively in the C-style functions which deals with conventional c-strings?

This is an old problem, which I have observed in past. So thought of getting a clarification once & for all. There are many standard / orthodox C library functions, which deal only with C-style strings. For example, my current implementation looks like this:

std::string TimeStamp (const time_t seconds)  // version-1
{
  auto tm = *std::localtime(&seconds);  // <ctime>
  char readable[30] = {}; 
  std::strftime(&readable[0], sizeof(readable) - 1, "%Y-%h-%d %H:%M:%S:", &tm);
  return readable;
}

Above works as expected. But as you can see, that the readable is copied from stack array to std::string. Now this function is called very frequently for logging & other purposes.

Hence, I converted it to following:

std::string TimeStamp (const time_t seconds)  // version-2
{
  auto tm = *std::localtime(&seconds);  // <ctime>
  std::string readable(30,0);
  std::strftime(&readable[0], readable.length(), "%Y-%h-%d %H:%M:%S:", &tm);
  return readable;
}

At unit test level, it apparently seems to work. But for overall logging in my much larger code, it somehow gets messed up. A new line character appears after this output & many of the output strings which are called outside this function are not printed. Such issue happens only when the "version-1" is changed to "version-2".
Even following modification also doesn't help:

readable.resize(1 + std::strftime(&readable[0], readable.length(), "%Y-%h-%d %H:%M:%S:", &tm));

Is there anything wrong in my code? What is the correct way of directly using std::string in the C-style string functions?

Aucun commentaire:

Enregistrer un commentaire