在c++中如何创建类似于snprintf的消息,并只更改消息中的值
How in c++ create message similar to snprintf and just change value in message?
我如何创建类似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.
相关文章:
- boost::进程间消息队列引发错误
- 在线编译器中的分段C++没有打印消息
- C++错误消息*成员参考.**初学者*
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何通过参数抛出错误消息
- 从服务器传输到客户端的消息不会出现
- ROS2 动态消息模板
- C++秘密消息学校作业
- glad 导致 glfwSwapBuffers 返回错误消息
- C++入门 5 版:类消息和文件夹
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 如何将 Firebase 与基于 Linux 的客户端应用配合使用,以便与服务器进行双向消息通信
- 重新定义预定义的 errno 错误消息 (E2BIG)
- Libmosquitto publish 不会将所有消息传递到 Azure IoT Hub
- 在c++中如何创建类似于snprintf的消息,并只更改消息中的值