1. 关键词
C++ 数据格式化 字符串处理 std::string int double 跨平台
2. strfmt.h
| #pragma once |
| |
| #include <string> |
| #include <cstdint> |
| #include <sstream> |
| #include <iomanip> |
| |
| namespace cutl |
| { |
| |
| |
| |
| |
| |
| |
| |
| |
| std::string fmt_uint(uint64_t val, uint8_t width = 0, char fill = '0'); |
| |
| |
| |
| |
| |
| |
| |
| std::string fmt_double(double val, int precision = 2); |
| } |
3. strfmt.cpp
| #include <sstream> |
| #include <iomanip> |
| #include <bitset> |
| #include "strfmt.h" |
| |
| namespace cutl |
| { |
| std::string fmt_uint(uint64_t val, uint8_t width, char fill) |
| { |
| std::stringstream ss; |
| ss << std::setfill(fill) << std::setw(width) << val; |
| return ss.str(); |
| } |
| |
| std::string fmt_double(double val, int precision) |
| { |
| std::stringstream ss; |
| ss << std::setiosflags(std::ios::fixed) << std::setprecision(precision) << val; |
| return ss.str(); |
| } |
| } |
4. 测试代码
| #include "common.hpp" |
| #include "strfmt.h" |
| |
| void TestFormatUintAndDouble() |
| { |
| PrintSubTitle("TestFormatUintAndDouble"); |
| |
| std::cout << "fmt_uint 1: " << cutl::fmt_uint(12) << std::endl; |
| std::cout << "fmt_uint 2: " << cutl::fmt_uint(12, 4) << std::endl; |
| std::cout << "fmt_uint 3: " << cutl::fmt_uint(12, 4, 'x') << std::endl; |
| std::cout << "fmt_double 1: " << cutl::fmt_double(3.141592653) << std::endl; |
| std::cout << "fmt_double 2: " << cutl::fmt_double(3.141592653, 3) << std::endl; |
| } |
5. 运行结果
| --------------------------------------TestFormatUintAndDouble--------------------------------------- |
| fmt_uint 1: 12 |
| fmt_uint 2: 0012 |
| fmt_uint 3: xx12 |
| fmt_double 1: 3.14 |
| fmt_double 2: 3.142 |
6. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战