我必须用sprintf
格式化std::string
并将其发送到文件流中。 我怎样才能作到这一点? ios
我使用vsnprintf编写了本身的脚本,所以它返回字符串,而没必要建立本身的缓冲区。 c++
#include <string> #include <cstdarg> //missing string printf //this is safe and convenient but not exactly efficient inline std::string format(const char* fmt, ...){ int size = 512; char* buffer = 0; buffer = new char[size]; va_list vl; va_start(vl, fmt); int nsize = vsnprintf(buffer, size, fmt, vl); if(size<=nsize){ //fail delete buffer and try again delete[] buffer; buffer = 0; buffer = new char[nsize+1]; //+1 for /0 nsize = vsnprintf(buffer, size, fmt, vl); } std::string ret(buffer); va_end(vl); delete[] buffer; return ret; }
因此你能够像这样使用它 git
std::string mystr = format("%s %d %10.5f", "omg", 1, 10.5);
您能够尝试如下方法: github
string str; str.resize( _MAX_PATH ); sprintf( &str[0], "%s %s", "hello", "world" ); // optionals // sprintf_s( &str[0], str.length(), "%s %s", "hello", "world" ); // Microsoft // #include <stdio.h> // snprintf( &str[0], str.length(), "%s %s", "hello", "world" ); // c++11 str.resize( strlen( str.data() ) + 1 );
根据Erik Aronesty提供的答案: this
std::string string_format(const std::string &fmt, ...) { std::vector<char> str(100,'\0'); va_list ap; while (1) { va_start(ap, fmt); auto n = vsnprintf(str.data(), str.size(), fmt.c_str(), ap); va_end(ap); if ((n > -1) && (size_t(n) < str.size())) { return str.data(); } if (n > -1) str.resize( n + 1 ); else str.resize( str.size() * 2); } return str.data(); }
这样避免了从原始答案中的.c_str()
结果中.c_str()
const
的须要。 google
我偏心的一种解决方案是在使所述缓冲区足够大以后,直接将sprintf放入std :: string缓冲区中: spa
#include <string> #include <iostream> using namespace std; string l_output; l_output.resize(100); for (int i = 0; i < 1000; ++i) { memset (&l_output[0], 0, 100); sprintf (&l_output[0], "\r%i\0", i); cout << l_output; cout.flush(); }
所以,建立std :: string,调整其大小,直接访问其缓冲区... c++11
google就是这样的: StringPrintf
(BSD许可证)
和facebook以很是类似的方式进行操做: StringPrintf
(Apache许可)
二者都还提供了方便的StringAppendF
。 code