我正在尝试编写一个类似于 C# 的 String::Format 的函数,它不是采用以“%”(“%d %s %i”)开头的参数,而是采用类似“{0} { 1} {2}”,我已经让它工作了(大部分)。
它正确地找到并替换了所有出现的地方,但是当它到达 args 的末尾时就会中断。就在它中断之前,调试器显示“结果”被设置为“\f;@”,其中最后一个字符是一个随机的“非标准”字符。
注意**:'string' 是 std::string,String::Format1 工作正常并使用 vsnprintf_s,String::Replace 查找并用 replace 替换所有出现的 find。
string String::Format2(const string format, ...)
{
string output = format;
va_list args;
va_start(args, format);
{
uint i = 0;
while (args[i] != NULL)
{
string find = String::Format1("{%i}", i);
// Breaks here
string replace = va_arg(args, const char*);
output = String::Replace(output, find, replace);
i++;
}
}
va_end(args);
return output;
}
最佳答案
感谢@Justin 的评论,为我指明了正确的方向。
我使用了可变参数模板,它似乎可以正常工作:)
找到我的答案 here
template<typename T, typename ... Args>
static string Format3(const string fmt, const T& first, const Args&... args)
{
std::stringstream stream;
stream << first << std::endl;
int sink[] = { 0, ((void)(stream << args << std::endl), 0)... };
(void)sink;
string out = fmt;
uint pos = 0;
while (stream.good())
{
string find = String::Format1("{%i}", pos);
string replace;
stream >> replace;
out = String::Replace(out, find, replace);
pos++;
}
return out;
}
关于C++ 遍历 va_list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44857283/