在c++中如何创建类似于snprintf的消息,并只更改消息中的值

How in c++ create message similar to snprintf and just change value in message?

本文关键字:消息 snprintf 类似于 何创建 c++ 创建      更新时间:2023-10-16

我如何创建类似snprintf的消息(其中我可以用%d表示整数的通用文本,并且当我需要在sprintf connect with parameter中显示时),以避免串联?(我需要创建类似You need more %d coins的结果字符串,目前我正在以错误的方式连接并返回值'You need more' + some_stringified_value + 'coins'

"规范"C++方法是使用stringstream,类似于以下内容:

std::string somefunc(int number)
{
  std::stringstream ss;
  ss << "You need " << number << " more coins";
  std::string str = ss.str();
  return str;
}

也可以在C++中使用snprintf:

int snprintf ( char * s, size_t n, const char * format, ... );

例如(来自上述链接):

/* snprintf example */
#include <stdio.h>
int main ()
{
  char buffer [100];
  int cx;
  cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );
  snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );
  puts (buffer);
  return 0;
}

输出:

The half of 60 is 30, and the half of that is 15.