c++ - vprintf 类似函数,但需要一个字符串 ID

标签 c++ mfc

我需要一些非常相似但有所不同的东西。

#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(an 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;
}

更新/理由

我总是可以先从 id 加载字符串,然后调用原始的 WriteFormatted() 函数,但我不想这样做的原因是我正在重构代码,这个调用在很多地方。所以我想传递字符串 id 并让函数加载该字符串,而不是我在每个地方都调用它。

最佳答案

如果您想将format-string 作为一种资源来管理,那么我建议按如下方式重写代码。我想 LoadString 返回一个 std::string;如果不是,请相应地调整代码。请注意,同时提供表示格式和格式的 ID 没有多大意义:然后您会将哪个传递给 vprintf?。希望对您有所帮助。

void WriteFormatted (int stringId formatId, ... )
{
  va_list args;
  va_start (args, formatId);
  std::string formatStr = LoadString(formatId);
  const char* format = formatStr.c_str();
  vprintf (format, args);
  va_end (args);
}

int main ()
{
   WriteFormatted (STRING_ID_ONE_ARGUMENT, 1);

   return 0;
}

关于c++ - vprintf 类似函数,但需要一个字符串 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46408578/

相关文章:

java - 为什么不能创建没有花括号的 1 语句函数?

c++ - “Transposed .txt file"带有随机字符,这可能吗?

visual-c++ - WS_EX_LAYERED、不可见窗口和全新安装的 Windows

c++ - 选择字体对话框 : munges font name fails to reload it

c++ - 我可以在不使用其 UI 框架的情况下将 Qt 用作 C++ 库吗

c++ - 将 vector 的 vector 打印到 ostream

c++ - 连续性多个 WSASend() io 完成端口

c++ - 使用虚拟继承时初始化基类

c++ - 在 C++/MFC 中混合和匹配类

c++ - MFC 错误如 A reference that is not to 'const' cannot be bound to a non-lvalue