int类型前面的0如何显示?

来源:百度知道 编辑:UC知道 时间:2024/05/09 10:10:04
定义接收一个四位整数,大于0001小于9999,若是接收到的是0009,在int中输出时只会输出9,为什么?怎么改?

请看下面的函数,加两个头文件,iostream这个应该知道,控制输入输出的,
iomanip是控制输出格式的。setw(5)函数实现输出占用几位的空间,cout.fill('0');这个函数实现空位补0;

#include<iostream>
#include <iomanip>
using namespace std;

int main()
{
int i=8;
cout.fill('0');
cout<<setw(5)<<i<<endl;
return 0;
}

默认的都是不会显示前面的0的
因为系统认为0009和9一样
如果想显示的话
建议用数组来实现
提示:字符数组
那样你就可以随心所欲了

笨办法:
int count=0;
while(num/10>0)count++;
for(int i=0; i<(4-count); i++)
cout<<"0";
cout<<num<<endl;