Datasheet
I/O streams are covered in depth in Chapter 14, but the basics of output are very simple. Think of an
output stream as a laundry chute for data. Anything you toss into it will be output appropriately.
std::cout is the chute corresponding to the user console, or standard out. There are other chutes,
including
std::cerr, which outputs to the error console. The << operator tosses data down the chute.
In the preceding example, a quoted string of text is sent to standard out. Output streams allow multiple
data of varying types to be sent down the stream sequentially on a single line of code. The following
code outputs text, followed by a number, followed by more text.
std::cout << “There are “ << 219 << “ ways I love you.” << std::endl;
std::endl represents an end of line character. When the output stream encounters std::endl, it will
output everything that has been sent down the chute so far and move to the next line. An alternate way
of representing the end of a line is by using the ‘
\n’ character. The \n character is an escape character,
which refers to a new-line character. Escape characters can be used within any quoted string of text. The
list below shows the most common escape characters.
❑
\n new line
❑
\r carriage return
❑
\t tab
❑
\\ the backslash character
❑
\” quotation mark
Streams can also be used to accept input from the user. The simplest way to do this is to use the
>> operator with an input stream. The std::cin input stream accepts keyboard input from the user.
User input can be tricky because you can never know what kind of data the user will enter. See
Chapter 14 for a full explanation of how to use input streams.
Namespaces
Namespaces address the problem of naming conflicts between different pieces of code. For example, you
might be writing some code that has a function called
foo(). One day, you decide to start using a third-
party library, which also has a
foo() function. The compiler has no way of knowing which version of
foo() you are referring to within your code. You can’t change the library’s function name, and it would
be a big pain to change your own.
Namespaces come to the rescue in such scenarios because you can define the context in which names are
defined. To place code in a namespace, simply enclose it within a namespace block:
// namespaces.h
namespace mycode {
void foo();
}
4
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 4