Use of setw() manipulator – CSKC
Sign In

Search

Code Learning #CPP#4310    siteicon   siteicon  

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

TC++ #4310

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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


Suggested Filename(s): setw.cpp



Share

Created: 15-May-2018 18:44 | Updated: 15-Sep-2018 16:05|