您可以从 c# 中创建一个几乎类似于 WriteLine 的函数:
void WriteLine(string const &outstr, ...) {
va_list placeholder;
va_start(placeholder, outstr);
bool found = false;
for (string::const_iterator it = outstr.begin(); it != outstr.end(); ++it) {
switch(*it) {
case '{':
found = true;
continue;
case '}':
found = false;
continue;
default:
if (found) printf("%s", va_arg(placeholder, char *));
else putchar(*it);
}
}
putchar('\n');
va_end(placeholder);
}
用类似的论点来称呼它:
WriteLine("My fav place in the world is {0}, and it has a lot of {1} in it", "Russia", "Mountains");
输出:
My fav place in the world is Russia, and it has a lot of Mountains in it
该函数当然并不完美,因为来自 c# 的 System.Console.WriteLine() 函数可以使争论不按顺序排列,并且仍然将正确的字符串放在完整字符串中的正确位置。这可以通过首先将所有参数放在一个数组中并访问数组的索引来解决