Public
Snippet $1655244 authored by Jesse

A function to return a string of time

Edited
stringTimeFunction.cpp
/*\
 * File: stringTimeFunction.cpp
 * Language: C++
 * Version: 0
 * Author: culb (nightfrog)
 * Contact: the01culb[at]gmail[dot]com
 *
 * Compile:
 *  clang++ -Wall -Wextra -pedantic -O3 -std=c++11 stringTimeFunction.cpp -o stringtime
 *  g++ -Wall -Wextra -pedantic -O3 -std=c++11 stringTimeFunction.cpp -o stringtime
 *
 * Note: Tested with clang 3.5 and gcc 4.9
 *
 * License:
 *  If this code is used in any way then
 *  be courteous and include all of my information and notes
\*/
 
#include <ctime>
#include <string>  /* string */
#include <cstdlib> /* exit */
#include <iostream>
 
std::string
TimeString( std::string formatString )
{
  std::time_t time = std::time( nullptr );
  struct tm *timeinfo = localtime( &time );
 
  std::string format;
 
  /* length will be positive and shouldn't be over 2 bytes(65535) */
  unsigned int length = strftime( &format[0], format.size(), formatString.c_str(), timeinfo );
 
  while( length == 0 )
  {
    /* if length is 0 then increase the size for the format */
    /* multiplying should increase the speed but the size wouldn't be precise */
    format.resize( format.size() + 1 );
    length = strftime( &format[0], format.size(), formatString.c_str(), timeinfo );
  }
 
  return format;
}
 
auto main() -> int
{
  std::string b = TimeString( std::string( "%A %c" ) );
 
  if( ! b.empty() )
  {
    std::cout << b.data() << std::endl;
    return( EXIT_SUCCESS );
  }
 
  return( EXIT_FAILURE );
}