有没有办法用C ++中的printf中的参数替换字符串?

时间:2018-01-31 23:25:40

标签: c++

我正在写一个本地化文件,有些文本需要输入数据......这让我想到了printf以及我们如何分配%s值然后继续添加参数来顺序替换它们。

喜欢这个......

printf("This is %s, their last name is %s", "Bob", "Jones");

是否有本机C ++方式执行此操作并将结果存储在字符串中?

3 个答案:

答案 0 :(得分:1)

C++我很可能会这样做:

std::string firstname = "Bob";
std::string lastname = "Jones";

std::ostringstream oss;

oss << "This is " << firstname << ", their last name is " << lastname;

std::string mystring = oss.str();

您仍可以std::printf使用std::sprintfC++ C++他们正式成为<#list entries as entry> <#assign entry = entry assetRenderer = entry.getAssetRenderer() entryTitle = htmlUtil.escape(assetRenderer.getTitle(locale)) viewURL = assetPublisherHelper.getAssetViewURL(renderRequest, renderResponse, entry) /> ... 标准的一部分。虽然它们不太安全。

答案 1 :(得分:0)

您可以使用任何类似variadic的现有printf功能,也可以创建自己的功能。请注意,许多人警告不要使用ellipsis,但有时,这是该工作所需要的。

int specialprintf(string fmt, ...) {
  int i;
  va_list vl;
  size_t n = std::count(fmt.begin(), fmt.end(), '%');
  va_start(vl,n);
  for (i=0;i<n;i++) {
     // do something with each arg
  }
  va_end(vl);
}

答案 2 :(得分:0)

在这种情况下,您可以使用variable arguments handling功能。通过使用变量参数编写自己的函数,您可以定义固定参数和未命名参数。以下是我的简单游戏引擎中DebugPrint函数的实现。

int DebugPrint(const char* file, const char* func, const int line, const char* fmt, ...)
{
    const size_t tempLength = 1024 + 1024;
    char temp[tempLength] = { 0 };
    sprintf_s(temp, fmt);
    va_list argp;
    const size_t outputLength = tempLength + 1024;
    char output[outputLength] = { 0 };
    va_start(argp, fmt);
    sprintf_s(temp, tempLength, "File: %s\n", file);
    OutputDebugStringA(temp);
    sprintf_s(temp, tempLength, "Func: %s\n", func);
    OutputDebugStringA(temp);
    sprintf_s(temp, tempLength, "Line: %d\n", line);
    OutputDebugStringA(temp);
    vsprintf_s(output, outputLength, fmt, argp);
    va_end(argp);
    OutputDebugStringA(output);
    OutputDebugStringA("\n");
    return 0;
}

OutputDebugStringA只允许我将输出打印到Visual Studio输出窗口而不是控制台。真正关注的是va_listva_startva_end

如果你想要#define,那么你不必每次都输入固定的参数,并且你知道那些参数的输入会被设置(在这种情况下,我将使用__FILE__,每当我调用此函数时,__FUNCTION____LINE__作为filefuncline的输入值,您可以执行以下操作:

#define DEBUG_LOG(fmt, ...) DebugPrint(__FILE__, __FUNCTION__, __LINE__, fmt, __VA_ARGS__)

每当我需要调用此函数时,我只会写:

DEBUG_LOG("This monster is at [%d, %d] now.\n", monsterList[i].GetPosition().GetX(), monsterList[i].GetPosition().GetY());

此函数将输出调用它的文件,函数和行以及您希望它输出的自定义数据。