Wednesday, August 31, 2011

Manipulators in C++ Programs


There is another manipulator setw in <b>C++ programs</b> to display values properly. This manipulator is available in iomanip.h header file. Values are by default displayed from the upper left corner (This is called left justified display). If we want to display out values with specified space, then we have to use setw manipulator. setw manipulator takes an integer value and will create imaginary field according to the integer value. Each box will contain one character and the values will be displayed in right justified order. Let’s see the working of setw manipulator with <b>C++ program</b>. 

#include< iostream.h >
#include< conio.h >
#include< iomanip.h >
void main ()
{
clrscr ();
cout<< setw (10)<<"12,235"<< endl;
cout<< setw (10)<<"1,000"<< endl;
cout<< setw (10)<< "2,35,000";
getch ();
}

Now observe the output of the  C++ programs using setw manipulator and without setw manipulator.
This setw manipulator can also be used to restrict the user from entering a string of more length than the size of a character type array.

void main ()
{
clrscr ();
char name [10];
cout << ”Enter any string with more than 9 characters: -“;
cin >>setw (10) >> name;
cout<< ”Entered string is: -“<< name;
getch ();
}

Reading multiple lines in C++ programs needs the use of get () function of cin object with different number arguments. The first two arguments are same as used to read multiple words. The third argument will be a special character that will be entered at the end although while displaying the value the character will not be displayed.

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ()
{
clrscr ();
char str [100];
cout<”Enter any string with multiple lines (at the end enter ‘!’); -”;
cin.get (str, 100,’!’);
cout<<”Entered string is: -“<< name;
getch ();
}



No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner