Sunday , 26 March 2017
Home » Tự học Lập Trình » Hướng đối tượng » setw() : Setting field width Using Cout in C++ Programming

setw() : Setting field width Using Cout in C++ Programming

setw() : Setting field width Using Cout in C++ Programming

  1. setw() is library function in C++.
  2. setw() is declared inside #include<iomanip>
  3. setw() will set field width.
  4. setw() sets the number of characters to be used as the field width for the next insertion operation.

Syntax :

setw(num)
  • num is width to be set in order to insert next value.

Live Example 1 : Setting Width in C++

#include <iostream>
#include <iomanip>

using namespace std;

int main () 
{
  cout << setw (10);
  cout << "Pritesh" << endl;

  return 0;
}
  1. Now Length of String Pritesh is 7
  2. We have set field width 10 so it will utilizes 7 fields
  3. Remaining 3 fields are kept blank.
  4. Default Justification : Left

Live Example 2 : Setting Width in C++

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
 const int maxCount = 4;
 const int width = 6;
 int row;
 int column;

 for(row=1;row<=10;row++)
 {
   for(column = 1; column <= maxCount; column++)
     {
     cout << setw(width) << row * column;
     }
   cout << endl;
 }

 return 0;
}

Output :

 1     2     3     4
 2     4     6     8
 3     6     9    12
 4     8    12    16
 5    10    15    20
 6    12    18    24
 7    14    21    28
 8    16    24    32
 9    18    27    36
10    20    30    40

Lượt xem (360)

About Nguyễn Thanh Sơn

Nguyễn Thanh Sơn
Network Security, Web Design, Computer Science

Xem thêm

header in c++

Tách chương trình lớn thành các file riêng

Tại sao cần phải tách Khi lập trình với bất cứ ngôn ngữ nào thì …

Để lại bình luận:

Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *