setw() : Setting field width Using Cout in C++ Programming
- setw() is library function in C++.
- setw() is declared inside #include<iomanip>
- setw() will set field width.
- 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; }
- Now Length of String Pritesh is 7
- We have set field width 10 so it will utilizes 7 fields
- Remaining 3 fields are kept blank.
- 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 (682)
Để lại bình luận: