Convert a number to a string with specified length in C++(在 C++ 中将数字转换为具有指定长度的字符串)
问题描述
我有一些不同长度的数字(如 1、999、76492 等),我想将它们全部转换为具有共同长度的字符串(例如,如果长度为 6,那么这些字符串将是:000001"、000999"、076492").
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492').
换句话说,我需要在数字中添加正确数量的前导零.
In other words, I need to add correct amount of leading zeros to the number.
int n = 999;
string str = some_function(n,6);
//str = '000999'
C++中有这样的函数吗?
Is there a function like this in C++?
推荐答案
或者使用stringstreams:
or using the stringstreams:
#include <sstream>
#include <iomanip>
std::stringstream ss;
ss << std::setw(10) << std::setfill('0') << i;
std::string s = ss.str();
我整理了我在 arachnoid.com 上找到的信息,因为我喜欢这种类型-iostreams 的安全方式更多.此外,您同样可以在任何其他输出流上使用此代码.
I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.
这篇关于在 C++ 中将数字转换为具有指定长度的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中将数字转换为具有指定长度的字符串
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01