在C ++中将数字转换为指定长度的字符串 [英] Convert a number to a string with specified length in C++

查看:587
本文介绍了在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 ++中有这样的函数吗? / p>

Is there a function like this in C++?

推荐答案

或使用stringstreams:

or using the stringstreams:

stringstream ss;
ss << setw(10) << setfill('0') << i;
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 ++中将数字转换为指定长度的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆