#include <iostream>
#include <cstdarg>
#include <string>
constexpr int kMaxSize = 512;
std::string StringFormat(const char* fmt, ...) {
char buffer[kMaxSize];
va_list args;
va_start(args, fmt);
int result = vsnprintf(buffer, kMaxSize, fmt, args);
va_end(args);
if ( result < 0) { /* error */
std::cout << "String Format Convert Error : " << kMaxSize << " " << result << std::endl;
} else if ( result > kMaxSize ) { /* warning */
std::cout << "String Format Convert Warning : truncated string" << std::endl;
}
return std::string(buffer);
}
int main(){
std::cout << StringFormat("hello %s","world") << std::endl;
return 0;
}
result:
[root@jn cpp]# g++ -std=c++11 testStringFormat.cpp
[root@jn cpp]# ./a.out
hello world
[root@jn cpp]#