我必須用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