C/C++ 输出间隔控制

来源:互联网 发布:nginx lua redis性能 编辑:程序博客网 时间:2024/06/06 14:21

C++使用setw(int n)来控制他后面的变量的输出占多少个位置。默认是右对齐。

例子:

#include <iostream>using namespace std;#include <iomanip>using std::setw;/*setw(int n)用来控制输出间隔。cout<<'s'<<setw(8)<<'a'<<endl;setw()只对其后面紧跟的输出产生作用表示'a'共占8个位置,不足的用空格填充。*/int main (){    int n[ 10 ]; // n 是一个包含 10 个整数的数组    // 初始化数组元素    for ( int i = 0; i < 10; i++ )    {      n[ i ] = i + 100; // 设置元素 i 为 i + 100    }    cout << "Element" << setw( 13 ) << "Value" << endl;    //                    setw(13)表示后面输出的Value占13个位置,前面不足的用空填充    // 输出数组中每个元素的值    for ( int j = 0; j < 10; j++ )    {      cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;    }    //setw()默认是右对齐的,可以设置左对齐    cout<<"------------------------------"<<endl;    cout<<std::left<<setw( 7 )<<9<< setw( 13 ) << n[9] << endl;    cout<<"------------------------------"<<endl;    cout<<setfill('#')<<setw( 7 )<<9<< setw( 13 ) << n[9] << endl;//上面设置了对齐是左对齐,这里还是保持左对齐    cout<<"------------------------------"<<endl;    //改回默认对齐,右对齐    cout<<std::right<<setfill('#')<<setw( 7 )<<9<< setw( 13 ) << n[9] << endl;    return 0;}
结果:

Element        Value      0          100      1          101      2          102      3          103      4          104      5          105      6          106      7          107      8          108      9          109------------------------------9      109------------------------------9######109##########------------------------------######9##########109Process returned 0 (0x0)   execution time : 0.097 sPress any key to continue.
C语言是在输出个数符前面加上数字或者小数点来实现的额,例如printf("%8d",n);这样后面的数n也是占8个位置,默认右对齐,

如果想要左对齐只要在百分号后面加一个减号就行了:printf("%-8d",n);

C语言例子:

#include<stdio.h>int main (){    int n[ 10 ]; // n 是一个包含 10 个整数的数组    // 初始化数组元素    int i;//C语中循环变量声明不能写到for循环里面    for (i= 0; i < 10; i++ )    {      n[ i ] = i + 100; // 设置元素 i 为 i + 100    }    printf("%s%13s\n","Element","Value");    // 输出数组中每个元素的值    int j;    for ( j = 0; j < 10; j++ )    {        printf("%7d%13d\n",j,n[j]);    }    printf("------------------------------\n");    printf("%-7d%-13d\n",9,9);    printf("------------------------------\n");    return 0;}
结果:

Element        Value      0          100      1          101      2          102      3          103      4          104      5          105      6          106      7          107      8          108      9          109------------------------------9      9------------------------------Process returned 0 (0x0)   execution time : 0.152 sPress any key to continue.



原创粉丝点击