[Code Snippet] String Formatting
CStringFormatter(const char*/wchar_t* Format, ...):
sprintf to a variable sized buffer all in one line of codez.
.h
Code:
// Credits to mmbob
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef _STRINGFORMATTER_H
#define _STRINGFORMATTER_H
#include <cstdarg>
#include <cstdio>
template <typename T>
class CStringFormatterT
{
T* s;
public:
CStringFormatterT(const T* pFormat, ...);
~CStringFormatterT()
{
delete[] s;
}
const T* Get() const
{
return s;
}
operator const T*() const
{
return s;
}
};
typedef CStringFormatterT<char> CStringFormatterA;
typedef CStringFormatterT<char> CStringFormatterW;
#if defined(UNICODE) || defined (_UNICODE)
typedef CStringFormatterW CStringFormatter;
#else
typedef CStringFormatterA CStringFormatter;
#endif
#endif
.cpp
Code:
//Credits to mmbob
#include "StringFormatter.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4996)
#endif
template <>
CStringFormatterT<char>::CStringFormatterT(const char* pFormat, ...)
{
va_list vArgs;
int CharsWritten;
int Size = 256;
do
{
s = new char[Size + 1];
va_start(vArgs, pFormat);
CharsWritten = vsnprintf(s, Size, pFormat, vArgs);
va_end(vArgs);
if (CharsWritten == -1)
{
delete[] s;
Size += 256;
}
} while (CharsWritten == -1);
}
template <>
CStringFormatterT<wchar_t>::CStringFormatterT(const wchar_t* pFormat, ...)
{
va_list vArgs;
int CharsWritten;
int Size = 256;
do
{
s = new wchar_t[Size + 1];
va_start(vArgs, pFormat);
CharsWritten = _vsnwprintf(s, Size, pFormat, vArgs);
va_end(vArgs);
if (CharsWritten == -1)
{
delete[] s;
Size += 256;
}
} while (CharsWritten == -1);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
use:
Code:
MessageBoxA(hWnd, CStringFormatter("here be your error: %d", Error), "error", MB_OK | MB_ICONERROR);
Code:
CStringFormatterW Str(L"%s", L"kkkkkkk");
Display(Str);