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++ 中将数字转换为具有指定长度的字符串


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09