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

查看:25
本文介绍了在 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++ 中将数字转换为具有指定长度的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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