Skip to content

Instantly share code, notes, and snippets.

@cjhanks
Created April 26, 2012 09:48
Show Gist options
  • Save cjhanks/2498330 to your computer and use it in GitHub Desktop.
Save cjhanks/2498330 to your computer and use it in GitHub Desktop.
LtoA and StringStreams
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using std::string;
char*
ltoa(long value, char* buf, const long& base)
{
memset(buf, '\0', 12);
long cnt = 12 - 1;
buf[cnt] = '\0';
bool is_negative = (value < 0);
do
{
buf[--cnt] = (value % base) + '0';
value /= base;
}
while(value);
int q = (is_negative) ? 1 : 0;
do
{
if (buf[q] != '\0')
{
memmove(buf, &buf[q], (12-1)-q);
memset(&buf[(12-1)-q], '\0', q);
break;
}
}
while(++q < (12 - 1));
return buf;
}
int
main(int argc, char* argv[])
{
char buf[12];
for (long i = 0; i < 4000000; ++i)
{
string q = ltoa(i, buf, 10);
}
}
#include <string>
#include "osstream2.h"
using std::string;
int
main(int argc, char* argv[])
{
for (long i = 0 ; i < 4000000; ++i)
{
ostringstream2 strm;
string q = (strm << i).str();
}
}
#ifndef OSSTREAM2_H_
#define OSSTREAM2_H_
#include <sstream>
using std::ostringstream;
class ostringstream2 : private ostringstream
{
public:
using ostringstream::str;
template <class T>
friend ostringstream2& operator<<(ostringstream2& os, T value)
{
static_cast<ostringstream&>(os) << value;
return os;
}
};
#endif //OSSTREAM2_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment