What exactly are cout/cin? - c++

I know Java and now want to learn C++. I can't understand what are cout (character output stream) and cin (character input). Are these global variables? Then why
"My message">>cout;
doesn't work? But
cout<<"My message";
works.

cout is an instance of the class std::ostream, and yes, it's a global variable. But operator>>(char *, ostream& os); hasn't been declared by the relevant header, so "My message">>cout; will give an error of something like "can't find an operator >> which takes arguments const char * and std::ostream" (and possibly a lot more errors because sometimes compilers get very confused by these sort of things).
cin is the same thing, except std::istream
If you really want to mess with peoples heads, you could do:
template<typename T>
std::ostream& operator>>(T x, std::ostream& os)
{
os << x;
return os;
}
Of course, it won't work for "My Message " >> "Some other string" >> cout;, which is probably one of the reasons it's not done that way.
Note that this is simply slight abuse of the operator overloading, where we have a custom type as the left-hand side, and standard or non-standard type on the right hand side. cout is no different from some other variable of a custom type.

std::cout and std::cin are indeed global variables. Your code doesn't compile because that's not the way the language works. You have to put the stream on the left, and then the operator and then the variables you are streaming into/out of. (For output, you can use literals and expressions as well as variables.)

consider the arrows as streams. << stands for output stream , while >> stands for input stream.
so cout << "hello" means output to screen
when cin >> a means asks from a user input for variable a
cout can also use "+" like for example you can add more strings to one stream like this
cout << "Hello" << "world" << "I am john";
cin in the same way can ask for input from multiple variables
cin >> a >> b ; will ask from user to input two times one for each variable

iostream is a header file which contain classes handling input and output operations for a console. Its like you create a object when you say "cin" for the input class handling input operation for a console in the header file. Same can be said about "cout" where a object is being created from a class handling output operation to a console in the header file.
When you consider "cin", imagine creating a pipe connected to the console and your program and an object "cin" taking your inputs from the console which you provide through your keyboard and dumping them on to the program. That's the reason you can see having a ">>" operator for cin and you can find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cin".
Whereas for "cout", imagine creating a pipe connected to the console and your program and an object "cout" taking its input from the program and dumping them on to the console. That's the reason you can see having a "<<" operator for cout and you find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cout".
So basically you need to first specify what object you would be creating for your operations and then assigning an operator to accomplish your task. If you include the header file, then its like you could use those objects anywhere throughout your program.
So, "My message">>cout; doesn't function the way you expect it to be because there is no object and an operator to accomplish your task whereas cout<<"My message"; does.
The technical aspects have been described by Mats Petersson. This is just to give you a general picture of what's actually happening pictorially. Hope this helps you.

Related

Question std::cout in C++ how exactly does the stream work?

Say we have:
std::cout << "Something";
How exactly is this working? I just want to make sure I understand this well and, from what I've been reading, is it okay to say that basically the insertion operator inserts the string literal "Something" into the standard output stream?
But what happens after that? Where does the standard output stream lead? Can anyone explain this?
That's basically the only part I don't get: I have the string literal "Something" in the standard output stream, but where does the stream lead?
The technical details vary between the different Operating Systems, but the basics are the same:
Every program has usually 3 standard streams: out (cout), in (cin), and err (cerr) (same as out, but used for errors). Those streams are nothing on their own; they exist to be used by a third party. That third party may be, for example, the terminal. When you execute a program form the terminal, it attaches to the program streams and show their output/request their input in the terminal.
If you wanted to do the same, you could execute a command yourself from your program, and take the out/in/err streams to read or write from/to them.
You have an example of that here: How do I execute a command and get the output of the command within C++ using POSIX?
Edit: When talking about C++, remember that cout << "anything" is just syntactic sugar for the function cout.operator<<("anything"). And that function "simply" writes to the stream
so,'std' is the namespace in which is stored everything found in the standard library , so basically you are saying "hey C++, go to 'std' storage and find cout command and run it" at least I know 'std' is this. and when you are saying using namespace std; you tell the compiler "take everything that's in the std namespace and dump it in the global namespace".
I hope it helped you to understand.

Allow user to name a class object

So, I ran into this problem while trying to create a text based game to play at work. :P
I wanted users to be able to make their new character, and the character object would be named, whatever they input. I know that I can just have a string variable that holds the name and use a counter, but even then, can I make the program change that? Here's an example.
(in this situation there is a menu that uses switch case, and another file with the class 'Character')
case: 1
string tempName;
cout << "Please enter the name of your new character." << endl;
cin >> tempName;
Character tempName();
Character.setName(tempName);
cout << "Congratulations! Your character " << Character.getName() << " has been created." << endl;
No, this just doesn't work.
First of all, the compiler must know all the variable names when the code is compiled. After compilation the names are gone and the executable file contains the binary code to be executed. That in itself makes it impossible to change the names later.
You also have a few other problems in your example code, so I bet you get quite a few confusing messages from the compiler. I'm sure the compiler itself is pretty confused by your attempts. :-)
First of all Character tempName(); doesn't declare an object of type Character, but the () at the end makes it declare a function returning a Character.
The fact that tempName already is the name of a string doesn't make it any better.
The next line Character.setName(tempName); is probably an attempt to call a function for a type. Interesting attempt, but it just doesn't work that way. The closes you have is Character::setName(tempName); if setName is a static member of class Character. But that would affect all objects of that type, not only a single one.
Oh, and I guess case: 1 is just a typo for case 1:.

Eclipse Luna C++ endl

I just started learning C++ and I noticed that when I do cout << "Some text" << endl; endl is not bold. I want to make sure that this is not a problem and it won't cause any future problems.
Do not (<---- this intentionally bold!) use std::endl! Ever. It has no place in C++. It was a good idea but it is being abused. If you want a newline, use '\n'. If you want a flush, use a std::flush. Here is a more thorough explanation.
I don't know about Eclipse but I'd assume that it highlight keywords in bold: std::endl isn't a keyword. It is just a function (well, actually it is a function template but the details really don't matter) with a specific signature (std::ostream&(std::ostream&)) pointers to which are treated special when using it with an output operator on a std::ostream: the operator will just call the function with the stream as argument. These functions are called manipulators.

What are 'aliased' stream buffers?

What are 'aliased stream buffers`? I encountered the term in a comment on an answer of mine.
I've never heard the term before, but in the thread you cite,
the person who used it also gave an example: two streams which
use the same streambuf.
Of course, just because two streams don't use the same
streambuf, doesn't mean that data written to them doesn't
ultimately end up in the same place; that they don't alias the
same sink, if that is what is meant. There are filtering
streambuf's, which forward the actual sinking and sourcing to
another streambuf, and on most systems, it's possible to open
a file at the system level, and connect a streambuf (or two) to
it.
--
James Kanze
It means an object with different name, for example this:
ostream &lbw = cout;
lbw << "Shahid out" << "Sachin in" << endl; //goes to cout!
What probably was meant in the comment there is this:
ofstream file;
file.rdbuf(cout.rdbuf());
// writes to cout
file << "hello";
So now the check there doesn't work:
if(&file == &cout)
// no, it doesn't

Convert from C++ style printing to my_printf()

C++ purists may want to look away now. You will hate this.
I have been given an open source windows console app that I am merging with a pre-existing, very old, very large windows app of my own. My old program started life as pure C though recently has been tweaked so that it can compile as C++. My program makes extensive use of a my_printf() function which prints text to a window.
The old console app does its printing C++ style via streams (I have never used this type of printing mechanism before).
When converting the console app to work under my system I could manually edit all the lines that do printing so that they use my_printf() instead. But before I embarked on that I thought I'd just check with StackOverflow to see if I was missing a trick. For example I could imagine somehow letting the C++ prints be done via the stream and then somehow scooping the final text somewhere and then calling my_printf() with the result. Might that be possible?
EDIT: please note my knowledge of C++ is extremely limited and I may need to look some things up in order to understand your answers so please use language that facilitates this.
There's indeed a trivial trick. But C++ impurists will hate the fact that C++ has a pure solution ;)
std::ostream is responsible for formatting, but not printing itself. That's handled by std::streambuf. std::cout combines a std::ostream formatter with a std::streambuf-derived object that writes to stdout.
However, you can change the streambuf backing an ostream with ostream::rdbuf(newbuf). As std::cout is just another ostream, you can replace its streambuf too. In this case, you only need to come up with a streambuf-derived class that writes already-formatted output to my_printf(). That should be quite trivial.
You might find string streams useful. For example:
std::ostringstream os;
os << "Print " << whatever << data;
my_printf( "%s", os.str().c_str() );
In case you were feeling adventurous, you could write your own streambuf instead that used my_printf underneath, and inject it into the stream object that is currently used in output statements (e.g. std::cout). Be warned that this latter approach might not be trivial, however it would result in almost no changes to existing codebase.
Subclass std::ostream and make operator << call my_print_f(). You can use internal stringstream in your stream to retrieve string representation of operator << arguments.
Then you'd just have to do find&replace, replacing cout (or whatever stream you directed your output to in the console app) with an instance of your stream class.
Something along these lines might be helpful:
http://www.codeproject.com/KB/debug/debugout.aspx
Should be obvious where the meat of it is, so you can make it print via your own systems, or what have you. In theory, you'd need only search for references to std::cout and replace them with references to your own object.
Overloading the global operator<< is probably what will solve your problem:
#include <iostream>
#include <cstdio>
static int
my_printf (const char* s)
{
printf ("my_printf: %s\n", s);
}
namespace std {
std::ostream& operator<< (std::ostream& out, const char* s)
{
my_printf (s);
return out;
}
}
int
main ()
{
std::cout << "hello, world"; // => my_printf: hello, world
return 0;
}