cin and cout

In C, the printf is most commonly used for output, and scanf or gets used for input. In C++, input and output are accomplished with the cin and cout classes. It is important to realize that cin and cout are not functions, but classes that contain many functions.

One thing that immediately confuses C programmers about cin and cout, is that they don't look like function calls at all. This is because the writers of the class have used a feature of C++ called operator overloading. Operator overloading allows you to write functions for your class that get called when a normal operator (such as '+', '-', or '<<') is used with your class. Don't let the appearance confuse you. As you learn more about class writing and operator overloading, it will all make sense.


cin

cin is either an ostream object (for STL compilers), or an ostream_with_assign for non-STL compilers. The definition described here applies to both. cin is used to get data into a program similar to scanf, or gets, from the keyboard. The format of using this object is:
cin >> Target;

With this, C++ will automatically determine the data type for Target (which is a variable), and store data in it. For example:

int I;
char Str[31];
cin >> I;
cin >> Str;

In this example, C++ will automatically convert keyboard input to an integer, and store it in I, and store the string the user types (after hitting ENTER) into the Str array.

cin has the ability to work with all the standard fundamental data types, and just about all the standard classes. You can also write an operator for your own classes that will permit them to be initialized by cin in a similar fashion.


cout

cout is similar to cin. It is either an ostream object, or an ostream_with_assign object. Like cin, cout automatically identifies the data type you are passing to it, and prints it accordingly. One primary difference, is that the output often needs a 'flush' signal (cin does also, but that's the user hitting the ENTER key). To send a 'flush' to the buffer, use endl. Examine the following example:

#include <iostream.h> // For non-STL compilers
// #include <iostream> // Uncomment for STL compilers
// using namespace std; // uncomment for VC++ and STL
void main( void )
{
	int I;
	char Str[128];
	cout << "What's your name?" << endl;
	cin >> Str;
	cout << "and what's your age?" << endl;
	cin >> I;
	cout << "Hi " << Str << " your " << I << "!" << endl;
}