用C ++转换数字 [英] converting number in C++

查看:70
本文介绍了用C ++转换数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中是否有任何函数将am数字转换为n?

例如:

m = 4,n = 8

输入:1234

输出:00001234

is there any function in C++ to convert a m digit number to n ?
for example :
m = 4, n = 8
input : 1234
output: 00001234

推荐答案

使用printf完成工作。



如果你在程序中看m和n是变量,那么你必须向printf发送一个包含你想要的格式的字符串。



printf (%08d,1234);



将根据需要输出00001234.



http://www.cplusplus.com/reference/cstdio/printf/ [ ^ ]
Use printf to do the job.

If you are looking at m and n being variables in your program, then you will have to send printf a string containing the format you want.

printf("%08d", 1234);

will output 00001234 as you want.

http://www.cplusplus.com/reference/cstdio/printf/[^]


您也可以使用 C ++ I / O 用于此目的的流:

You may also use C++ I/O streams for the purpose:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  cout << setfill('0') << setw(8) << 1234 << endl;
}


其他2个答案完全足够。我喜欢溪流方法。如果你想要一个使用printf()的一般方法,那么:





The other 2 answers are fully adequate. I like the streams approach. If you want a general approach using printf() then:


int value=1234;
int width = 8;
printf ("%0*d \n", width, value);


这篇关于用C ++转换数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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