C++字符串格式化的几种方式

C++字符串格式化的几种方式使用 snprintf 使用 boost format 使用 stringstream 具体示例使用 snprintf include stdio h usingstd string 准备数据 stringhaha haha intnum 3 准备格式 stringfmt teststring s testnumber stdio h

  1. 使用snprintf格式化字符串
  2. 使用boost::format格式化字符串
  3. 使用stringstream格式化字符串

具体示例

  1. 使用snprintf格式化字符串
#include <stdio.h> using std::string; // 准备数据 string haha("haha"); int num = 3; // 准备格式 string fmt("test string: %s. test number: %d"); char targetString[1024]; // 格式化,并获取最终需要的字符串 int realLen = snprintf( targetString, sizeof(targetString), fmt.c_str(), haha.c_str(), num ); 

参考链接:http://www.cplusplus.com/reference/cstdio/snprintf/

  1. 使用boost::format格式化字符串
#include "boost/format.hpp" // 准备数据 string haha("haha"); int num = 3; // 准备格式 boost::format fmt("test string: %s. test number: %d"); // 格式化 fmt % haha % num; // 获取最终需要的字符串 string targetString = fmt.str(); 

参考链接:https://www.boost.org/doc/libs/1_70_0/libs/format/example/sample_formats.cpp

  1. 使用stringstream格式化字符串
#include <sstream> using std::stringstream; // 准备数据 string haha("haha"); int num = 3; // 准备根据格式造字符串流 stringstream fmt; /* 或者使用 ostringstream */ // 造字符串流 fmt << "test string: " << haha << ". test number: " << num; // 获取最终需要的字符串 string targetString = fmt.str(); 

参考链接:http://www.cplusplus.com/reference/ostream/ostream/operator<

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231957.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • BeanUtils_BeanUtils

    BeanUtils_BeanUtilsBeanUtils类依赖的jar包注意:其中第二个包一定是commons-collections-xxx.jar,之前使用了commons-collectionsx-xxx.jar在web上显示未找到类BeanUtils类当中的主要方法populate(Objectbean,Map<String,?extendsObject>properties):可以将pr…

    2025年10月26日
    4
  • MySQL数据库备份与还原

    MySQL数据库备份与还原#第一种通过命令:mysqldump-uroot-p密码需要备份的数据库名&gt;备份后的sql脚本名;cmd–&gt;mysqldump-uroot-proot16jike2_account&gt;D:\16jike2_account_back.sql注意:备份名称与原数据库名称一致!通常:备份数据库名_back.sql还原备份的文件数…

    2022年4月29日
    49
  • kill命令杀死所有进程_ubuntu杀死进程命令

    kill命令杀死所有进程_ubuntu杀死进程命令常规篇: 首先,用ps查看进程,方法如下:$ps-ef……smx      1822    1 011:38?       00:00:49gnome-terminalsmx      1823 1822 011:38?       00:00:00gnome-pty-helpersmx      1824 1822 011:38

    2022年9月21日
    3
  • 查看 CUDA 版本 正确方法(亲测有效)

    查看 CUDA 版本 正确方法(亲测有效)查看CUDA版本正确方法!(亲测有效)

    2022年4月29日
    387
  • idea激活码最新【最新永久激活】

    (idea激活码最新)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.htmlZ9LZO4ZKWA-eyJsa…

    2022年3月22日
    68
  • 搞清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop

    搞清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop转载自:https://www.imooc.com/article/17571网页可见区域高:document.body.clientHeight网页正文全文高:document.body.scrollHeight网页可见区域高(包括边线的高):document.body.offsetHeight网页被卷去的高:document.body.scrollTop屏幕分辨率高:window.screen…

    2022年7月24日
    14

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号