我的c++学习(4) C++输入输出格式的控制

默认进制:默认状态下,数据按十进制输入输出。如果要求按八进制或十六进制输入输出,在cin或cout中必须指明相应的数据形式,oct为八进制,hex为十六进制,dec为十进制。

#include "stdafx.h"
#include<iostream>
using namespace std;
int main(void){  

 int i, j, k, l;
     cout<<"Input i(oct), j(hex), k(hex), l(dec):"<<endl;
     cin>>oct>>i; //输入为八进制数
     cin>>hex>>j; //输入为十六进制数
     cin>>k; //输入仍为十六进制数
     cin>>dec>>l; //输入为十进制数
     cout<<"hex:"<<"i="<<hex<<i<<endl;
     cout<<"dec:"<<"j="<<dec<<j<<'	'<<"k="<<k<<endl;
     cout<<"oct:"<<"l="<<oct<<l;
     cout<<dec<<endl; //恢复十进制输出状态

}

数据间隔
常用设置方法:输出空格符或回车换行符。
指定数据输出宽度:用C++提供的函数setw()指定输出数据项的宽度。setw()括号中通常给出一个正整数值,
用于限定紧跟其后的一个数据项的输出宽度。如:setw(8)表示紧跟其后的数据项的输出占8个字符宽度。

#include "stdafx.h"
#include<iostream>
using namespace std;
#include<iomanip>
int main(void){   
     int i=2,j=3;
     float x=2.6,y=1.8;
     cout<<setw(6)<<i<<setw(10)<<j<<endl;
     cout<<setw(10)<<i*j<<endl;
     cout<<setw(8)<<x<<setw(8)<<y<<endl;
}


几点说明:

1.如果数据的实际宽度小于指定宽度,按右对齐的方式在左边留空,如果数据的实际宽度大于指定宽度,则按实际宽度输出,即指定宽度失效。
2.setw()只能限定紧随其后的一个数据项,输出后即回到默认输出方式。
3.使用setw()必须在程序开头再增加一句: #include<iomanip>

原文地址:https://www.cnblogs.com/yangwujun/p/3310206.html