setw()函式使用,#include ——using std::setw;
阿新 • • 發佈:2018-12-18
使用時宣告:
#include <iostream> using namespace std; #include <iomanip> using std::setw;
cout<<'s'<<setw(8)<<'a'<<endl; 則在螢幕顯示s a //s與a之間有7個空格,
上程式碼:
#include <iostream> using namespace std; #include <iomanip> using std::setw; int main () { cout << "Element" << setw( 13 ) << "Value" << endl; cout<<"1"<<setw(6)<<"1"<<endl;
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; // 輸出陣列中每個元素的值 for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; }
return 0; }
結果:
Element Value 1 1 Element Value 0 100 1 101 2 102 3 103 4 104 5 105 6 106 7 107 8 108 9 109