2016-05-09 1 views
-4

Я использую C++ 11. Я хочу написать функцию, которая получает форматированную строку, и args (не знаю, сколько должно быть переменным) и возвращает полная строка.получить полную строку, имея формат и args C++

, например:

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; 

и возвращаемым значением является строка, которая выглядит следующим образом:

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

любой эффективный способ сделать это?

+0

Что вы имеете в виду [ 'станд :: snprintf'] (http://en.cppreference.com/ж/CPP/Io/с/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():

char buf[1000]; 
int bytes = snprintf(buf, sizeof(buf), format, INDEX_RECORD_TYPE_TIMESTAMP, 
    FORMAT_VERSION, optimizeBlockId, writeBlockId, timestamp); 
assert(bytes < sizeof(buf)); 
string result(buf, min(sizeof(buf), bytes)); // now you have a C++ string 
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