formatstdsting.h
#include <string>
#include <stdarg.h>
std::string format(const char *fmt, ...);
std::string format_arg_list(const char *fmt, va_list args);
formatstdstring.cpp
#include "formatstdstring.h"
#pragma warning(disable:4996)
std::string format(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
std::string s = format_arg_list(fmt, args);
va_end(args);
return s;
}
std::string format_arg_list(const char *fmt, va_list args)
{
if (!fmt) return "";
int result = -1, length = 256;
char *buffer = 0;
while (result == -1)
{
if (buffer) delete [] buffer;
buffer = new char [length + 1];
memset(buffer, 0, length + 1);
result = _vsnprintf(buffer, length, fmt, args);
length *= 2;
}
std::string s(buffer);
delete [] buffer;
return s;
}
example.cpp
#include <stdio.h>
#include "formatstdstring.h"
std::string getAsm() {
std::string s = "";
s.append(format("%08x %s", 0x401000, "MOV EAX, EAX\n"));
s.append(format("%08x %s", 0x401002, "RETN\n"));
return s;
}
void main() {
printf("%s", getAsm().c_str());
}
Java의 StringBuffer나 format 쓰던 습관이 남아서 이런 것들이 필요하다.