Stream Manipulators!!


Ok, recently I designed a program. In the program I wanted the user to enter his choice of yes or no. To save space, I chose to make the choice variable a bool value. Now, The problem that aroused was that the boolean choice inputted by the user required it to be 0 or 1. This didn’t look nice to me. So, I went to one of the forums to ask for a solution, and they suggested me a really good answer.. Using stream manipulators..

The link to the thread created by me is: daniweb. You can easily view it and see the comments too.

The thread also links you to the different sites speaking about the same topic.

To those, who ain’t willing to fo anywhere, Just understand the simple program:

#include <iostream>
using namespace std;
int main(){
bool a = false;
cout << "Are you awesome? ";
if (!(cin >> boolalpha >> awesome))
{
cin.clear();
cin >> noboolalpha >> awesome;
}
if (awesome)
cout << "You *are* awesome!" << endl;
else
cout << "Loser" << endl;
}

 

Ok, that wasn’t a simple one.. Here, the “boolalpha” and “noboolalpha” are the stream manipulators which forces the stream to take input “true” as 1 and “false’ as 0.
And based on the choice, it tells the computer to print the required output…
Hope, it’s clear..!!
Advertisements
Explore posts in the same categories: C++

Tags: , , ,

You can comment below, or link to this permanent URL from your own site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: