Use of setw() manipulator – Computer Sir Ki Class
  

Login
[lwa]



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

#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
int main()
{
clrscr();
char str[]="Hello";
cout<<setw(5)<<str<<endl;
cout<<setw(6)<<str<<endl;
cout<<setw(7)<<str<<endl;
cout<<str<<endl;
float f=3.1416;
cout<<f<<endl;
cout<<setw(10)<<f<<endl;
getch();
return 0;
}

Source Code

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char str[]="Hello";
cout<<setw(5)<<str<<endl;
cout<<setw(6)<<str<<endl;
cout<<setw(7)<<str<<endl;
cout<<str<<endl;
float f=3.1416;
cout<<f<<endl;
cout<<setw(10)<<f<<endl;
return 0;
}

Test it !

Run Output

Hello
Hello
Hello
Hello
3.1416
3.1416

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

sunmitra| Created: 15-May-2018 | Updated: 15-Sep-2018|






Back