Use of setw() manipulator
Demonstration of setw manipulation for setting display width
Learning Objectives
- Learning to use setw io manipulator to set field width for text as well as numbers.
Source Code
|
Run Output
Code Understanding
#include <iomanip>
This include file is required for all IO manipulation for display purposes.
char str[]=”Hello”;
This string will be used for display
cout<<setw(5)<<str<<endl;
Since the string is of 5 characters setting display width to 5 will not have any effect.
cout<<setw(6)<<str<<endl;
Now the width is set to 1 more than given string width so the string will be printed after leaving 1 space.
cout<<setw(7)<<str<<endl;
Here the string hello will be printed after leaving 2 spaces.
cout<<str<<endl;
Here the string will again be printed from start of the line. This also demonstrates that previous effect of setw will not be there.
float f=3.1416;
This decimal number will be used to test the affect of setw on numbers.
cout<<f<<endl;
This is number printing from the left most column.
cout<<setw(10)<<f<<endl;
Since the number is of 6 digits including the decimal so it will start printing after leaving first 4 columns as the width has been set to 10 columns.
Notes
- setw reference can be seen at
http://www.cplusplus.com/reference/iomanip/setw/
Suggested Filename(s): setw.cpp
sunmitra| Created: 15-May-2018 | Updated: 15-Sep-2018|