setf method for left and right alignment in a display field – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #CPP#4318    siteicon   siteicon  

setf method for left and right alignment in a display field

Use of setf method of cout to align content as left or right in a display field.

Learning Objectives

  • Learning setf to align content within there fields in a left and right aligned fashion.
  • Learning to unset the alignment formatting.
  • Learning the persistent bahaviour of setf method.

Source Code

TC++ #4318

#include 
#include
#include
int main()
{
clrscr();
char str[]="Hello";
cout.setf(ios::left);
cout< cout.unsetf(ios::left);
cout< cout.setf(ios::right);
cout< getch();
return 0;
}

Source Code

 

Test it !

Run Output

Hello     Hello
Hello Hello
Hello Hello

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.setf(ios::left);
This will set format for all subsequent display fields to aligned left in there field area. By default the content is aligned to right in its respective field area.

cout<<setw(10)<<str<<setw(10)<<str<<endl;
Hello will be printed twice with both field set to size of 10 and content aligned to left. Notice that setf is persistent in nature and it is not required to be set again and again for every field.

cout.unsetf(ios::left);
Since setf is persistent in nature we need to unset it to come to normal default status.
cout<<setw(10)<<str<<setw(10)<<str<<endl;
This will print the content as default way of fitting content towards the right of the given field width.

cout.setf(ios::right);
This is done for right alignment of content. This is useful when tabulated entry has to be printed.

cout<<setw(10)<<str<<setw(10)<<str<<endl;
This will print the content in right aligned form.

Common Errors

  • Commonly learners forget to set has a persistent behaviour unlike setw.


Suggested Filename(s): setwsetf.cpp



Share

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






Back