2016-05-09 5 views
-4

私はC++ 11を使用しています。フォーマットされた文字列とargs(いくつの変数が必要かを知らない関数)を書いて、フルストリング。例えばformatとargsの間に完全な文字列を取得するC++

"TimeStampRecord Type=3 Version=1 OptimizeBlockID=549 WriteBlockID=4294967295 Timestamp=1668" 

任意の効率的な方法がそうする:

format = "TimeStampRecord Type=%u Version=%u OptimizeBlockID=%u WriteBlockID=%u Timestamp=%lu" 

INDEX_RECORD_TYPE_TIMESTAMP = 3; 
FORAMT_VERSION = 1; 
optimizeBlockId = 549; 
writeBlockId = 4294967295; 
timestamp = 1668; 

、戻り値は文字列のように見えるのですか?

+0

何を、あなたは意味[ 'のstd :: snprintf'](http://en.cppreference.com/w/cpp/io/c/fprintf)? –

+0

['autosprintf'](http://doc.gnu-darwin.org/libasprintf/autosprintf.html)、[' Boost.Format'](http://www.boost.org/doc/libs/1_60_0/) libs/format /) –

+0

どうすればいいですか?http://abel.web.elte.hu/mpllibs/safe_printf/index.html –

答えて

0

Boost Formatを使用できます。または良い古いsprintf()

0

上記のようにsnprintfを使用できます。場合 はあなた自身でそれを実装したり、独自のプレースホルダを使用したい:

#include "iostream" 
#include "string" 

void formatImpl(std::string& fmtStr) { 
} 

template<typename T, typename ...Ts> 
void formatImpl(std::string& fmtStr, T arg, Ts... args) { 
    // Deal with fmtStr and the first arg 
    formatImpl(fmtStr, args...); 
} 

template<typename ...Ts> 
std::string format(const std::string& fmtStr, Ts ...args) { 
    std::string fmtStr_(fmtStr); 
    formatImpl(fmtStr_, args...); 
    return fmtStr_; 
} 


int main() { 
    std::string fmtStr = "hello %your_placeholder world"; 
    std::cout << format(fmtStr, 1, 'a') << std::endl; 
    return 0; 
} 

https://godbolt.org/g/hFwiS0

関連する問題