setw()函数使用,#include <iomanip> ——using std::setw;

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38998213/article/details/83539843

使用时声明:

#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

猜你喜欢

转载自blog.csdn.net/qq_38998213/article/details/83539843