首页 > 编程学习 > c++ 输出格式的变化示例

c++ 输出格式的变化示例

发布时间:2022/11/6 16:34:07

前言

c++ 输出格式的变化示例

Code

#include<iostream>
using namespace std;

int main(int argc, char const *argv[])
{
    char c[30]="this is string";
    double d = -1231.232;
    cout.width(30);
    cout.fill('*');
    cout.setf(ios::left);
    cout<<c<<"----L1"<<endl;
    cout.width(30);
    cout.fill('-');
    cout.setf(ios::right);
    cout<<c<<"----L2"<<endl;
    cout.setf(ios::dec|ios::showbase|ios::showpoint);
    cout.width(30);
    cout<<d<<"----L3"<<"\n";
    cout.setf(ios::showpoint);
    cout.precision(10);
    cout.width(30);
    cout<<d<<"----L4"<<"\n";
    cout.width(30);
    cout.setf(ios::oct,ios::basefield);
    cout<<100<<"----L5"<<"\n";
    // system("pause");
    return 0;
}

result

this is string****************----L1
----------------this is string----L2
-----------------------1231.23----L3
-------------------1231.232000----L4
--------------------------0144----L5

简洁版code

#include<iostream>
#include<iomanip>
using namespace std;
int main(){
    char c[30]="this is string";
    double d=-1234.8976;
    cout<<setw(30)<<left<<setfill('*')<<c<<"----L1"<<endl;
    cout<<setw(30)<<right<<setfill('*')<<c<<"----L2"<<endl;
    //showbase显示数值的基数前缀
    cout<<dec<<showbase<<showpoint<<setw(30)<<d<<"----L3"<<"\n";
    //showpoint显示小数点
    cout<<setw(30)<<showpoint<<setprecision(10)<<d<<"----L4"<<"\n";
    //setbase(8)设置八进制
    cout<<setw(30)<<setbase(16)<<100<<"----L5"<<"\n";
    // system("pause");
    return 0;
}

result

this is string****************----L1
****************this is string----L2
**********************-1234.90----L3
******************-1234.897600----L4
**************************0x64----L5
Copyright © 2010-2022 dgrt.cn 版权所有 |关于我们| 联系方式