0
我需要一些非常相似但有变化的东西。vprintf喜欢的功能,但需要一个字符串ID
#include <stdio.h>
#include <stdarg.h>
void WriteFormatted (const char * format, ...)
{
va_list args;
va_start (args, format);
vprintf (format, args);
va_end (args);
}
int main()
{
WriteFormatted ("Call with %d variable argument.\n",1);
return 0;
}
我上面想不同的是,第一个参数是一个字符串ID(一个int
)。该函数然后将相应的字符串加载到该ID并应用格式。这是否有可能以一种好的方式?
所以我建议的函数签名会变得像下面的样子,但是使用它不太合理,因为第二个参数必须是一个字符串。
void WriteFormatted3(int stringId, const char * format, ...)
{
// for demo, assume the following string corresponds to the stringId (hardcoded for this demo)
// just we can we run this without LoadString() id in a simple console application
char * str = "assume the id passed %d correspond to this string";
va_list args;
va_start(args, format);
vprintf(str, args);
va_end(args);
}
int main()
{
WriteFormatted (STRING_ID_ONE_ARGUMENT, "1"); // 1 has to be string or it will not compile
return 0;
}
更新/ justifcation
我总是可以从ID首先加载字符串,然后调用原始WriteFormatted()函数,但我不想这样做的原因是我的重构代码和这个电话是很多地方。所以我想传递字符串id并让函数加载那个字符串,而不是我在每个地方调用它。
那么这些Id和字符串如何存储? – Elemental
@Elemental其资源字符串。 Basicall使用LoadString(id)函数加载它。这部分非常简单。 – zar
我不明白为什么你认为你需要第二个参数是一个字符串。 – Elemental