10.3. Input / Output

Standard C mechanisms for I/O (printf, scanf, getchar, …) work as expected in C++.

C++ also defines objects for common I/O streams of data. Operator overloading is also used to provide a somewhat unique optional syntax for I/O. cout is the object which displays data on stdout. cin reads from stdin.

#include <iostream>

using std::cout;
using std::cin;
using std::endl;
// Or replace above lines with:
// using namespace std;

int main(void)
{
   int i;

   cout << "Enter a value for i: ";
   cin >> i;
   cout << "\nYou typed: " << i << endl;

   return 0;
}

Note that endl can be used to generate a return, like \n

Note the using statements in the above code. This is to resolve the namespace of these identifiers. In large programs, which use code potential coming from many sources. Conflict of identifier names can be a problem. C++ uses namespaces to resolve this problem. The full name of cout, for example, is actually std::cout. std is the namespace and :: is the scope resolution operator. If we know that we don’t have any other identifiers using the name cout. Then, we can shorten our syntax from std::cout to just cout if we specify a using statement as: using std::cout.

It may be simpler to just use the line: using namespace std;. This makes the shorter names of all identifiers in standard library available. The only drawback to this is that the list of available identifiers for use is reduced.

These I/O stream objects automatically print data according to its type. So a format statement telling the printing facility how to handle variables, i.e., %d, %f, %s …, are not needed.

Programmers can add facilities to print data belonging to a class type in a way that makes sense for the specific class. For example, consider a class for rational numbers (fractions). [1]

ostream & operator << (ostream & out, const rational & value)
{
   out << value.numerator() << '/' << value.denominator();
   return out;
}

Now having overloaded the << operator, we can use cout to print a rational number.

rational frac(3, 4);
cout << frac << endl;
[1]See operator overloading for more details.