现在的位置: 首页 > 综合 > 正文

C++的格式化输出(代码例子)

2013年11月25日 ⁄ 综合 ⁄ 共 1839字 ⁄ 字号 评论关闭
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
    int a = 1314;
    double pi = 3.14;
    string str = "********************我是可爱的分割线********************";
    cout << "hello word" << endl;
    cout << hex << a << endl;       //16进制数
    cout << oct << a << endl;       //8进制数
    cout << dec << a << endl;       //10进制数
    cout << str <<endl;
    //上面的是控制输出的不同进制的数

    cout << setw(3) << a << endl;
    cout << setw(4) << a << endl;
    cout << setw(5) << a << endl;
    cout << setw(6) << a << endl;
    cout << str << endl;
    //setw是操作子,setw只对紧跟的起作用,使用时需包含头文件<iomanip>,声明std命名空间

    cout << setfill('*') << setw(7) << a << endl;
    cout << str << endl;
    //setfill一旦设定,对以后的所有输出操作都生效
    //setfill需要配合着setw来使用
    //如想取消设定,则再用一次setfill(' ');

    cout << setiosflags(ios::right) << setw(10) << a << endl;

cout.width(10);
cout.setf(ios::right);//和setiosflags(ios::right);的作用相同
    cout << a << endl;
    cout.width(10);
    //cout << setfill(' ');//这样,就可以使其从星号的填充变回到空格填充
    cout << a << endl;
    cout << str << endl;
    //setw是操作子,width是成员函数。他们的作用相同

    cout << setiosflags(ios::showpoint) << pi << endl;//强制显示小数点和尾0
    cout << setiosflags(ios::showpos) << pi << endl;//强制显示符号(对后面都控制)
    cout << str << endl;

    cout << resetiosflags(ios::showpos);//取消强制显示符号。
    cout << setiosflags(ios::scientific) << pi << endl;  //科学计数法输出
    cout << setiosflags(ios::fixed) << pi <<endl;        //定点数
    cout << str << endl;

    cout << setprecision(2) << pi << endl;
    cout << setprecision(3) << pi << endl;
    cout << setprecision(4) << pi << endl;
    cout << setprecision(5) << pi << endl;
    cout << str << endl;
    //setprecision来设置精度(有效数字),自动四舍五入

    int num = 510;
    cout << hex << num << endl;//默认是16进制小写输出
    cout << setiosflags(ios::uppercase) << num << endl;//对一下输出均生效
    cout << hex << num << endl;
    cout << resetiosflags(ios::uppercase);//取消大写输出的设置
    cout << hex << num << endl;
    cout << str << endl;


    //用流成员函数put();输出字符
    //反序输出字符串的例子
    char s[] = "my name is sincerefly";
    for(int i = sizeof(s)/sizeof(s[0])-1; i!=0; --i) {
        cout.put(*(s+i-1));
    }
    cout << '\n' ;
    cout << str << endl;

//    char ch;
//    while((ch = cin.get())!= EOF) {  EOF这里报错,暂未解决
//        cout.put(ch);
//    }

    char ss[40];
    cout << "请输入一个字符串:" << endl;
    cin.get(ss, 40, '\n');
    cout << ss << endl;
    //cin.get的例子

    return 0;
}

很多种控制格式化输出的用法。基本的需要都能解决的。

【上篇】
【下篇】

抱歉!评论已关闭.