当前位置:C++技术网 > 资讯 > C++代码系统:cout

C++代码系统:cout

更新时间:2019-04-24 18:46:52浏览次数:1+次

代码名称:
cout

代码功能:
演示cout的各种使用使用方式,包括设置宽度、填充字符、对齐方式、有效位数、布尔值显示

源代码:

#include <iostream>
using namespace std;
int main()
{
    //指定宽度
    cout.width(8); //指定宽度值。仅对当次设置的输出流产生影响,下一次输出需要重新设置
    //指定填充,默认填充0
    cout.fill('-');//指定填充字符。填充字符一直有效,直到下一次设置覆盖

    //整数:长度 填充
    //整数常量和变量
    cout << 12 << endl; 
    int a = 12;
    cout << a << endl;

    //指定宽度并前置填充
    cout.width(10);
    cout.fill('-');
    cout << 12 << endl;

    //小数:长度 填充 小数点后个数 进位
    //小数常量和数字变量
    cout << 12.12454 << endl;
    double b = 12.12454;
    cout << b << endl;

    //指定宽度
    cout.width(10);
    cout.fill(' ');
    cout << b << endl;

    //指定有效位长度
    cout.precision(5);
    cout << b << endl;

    //指定小数点后有效位长度
    cout.flags(ios::fixed);
    cout.precision(2);
    cout << b << endl;

    //显示小数点后面的0,相当于后面填充0补齐宽度
    cout.flags(ios::fixed);
    cout.precision(8);
    cout.setf(ios::showpoint);
    cout << b << endl;

    //字符:
    //字符常量和变量
    cout << 'A' << endl;
    char ch = 'A';
    cout << ch << endl;

    //指定字符宽度
    cout.width(8);
    cout << ch << endl;

    //指定字符填充
    cout.width(8);
    cout.fill('-');
    cout << ch << endl;

    //设置对齐方式,默认右对齐
    cout.setf(ios::left);
    cout.width(8);
    cout.fill('-');
    cout << ch << endl;


    //数组:对齐方式、填充字符、宽度和前面一样设置
    //字符数组常量
    cout << "hello" << endl;
    char h[10] = "hello";
    cout.width(8);
    cout.setf(ios::right);
    cout << h << endl;

    //string:对齐方式、填充字符、宽度和前面一样设置
    string str = "world";
    cout.width(8);
    cout.setf(ios::right);
    cout << str << endl;

    //布尔变量
    cout << true << endl;     // 直接输出布尔变量,则显示数字0或1
    cout << boolalpha << true << endl;     // 要显示bool值,需要先设置格式

    return 0;
}


代码说明:
常用的设置cout格式的使用说明和示例,都在代码里了。

备注: