4.3 The std::cout Output Object

I l @ ve RuBoard

The standard object std::cout is used to output data to the console. We'll learn what a object is later in Chapter 13, but for now all we have to know is that the operator << [2] tells C++ what to output.

[2] Technically << is the left shift operator; however, the std::cout object has overloaded this operator and made it the output operator. (See Chapter 16 for a complete discussion of I/O objects and classes and Chapter 18, for a definition of overloading.)

So the statement:

 std::cout << "Hello World\n"; 

tells C++ to take the string " Hello World\n " and write it to the console. Multiple << operators may be used together. For example, both the following lines output the same message:

 std::cout << "Hello World\n"; std::cout << "Hello " << "World\n"; 

Expressions can also be output this way, such as:

 std::cout << "Half of " << 64 << " is " << (64 / 2) << "\n"; 

When this is executed, it will write:

 Half of 64 is 32 

on the console. Note that we had to put a space after the "of" in "Half of". There also is a space on either side of the "is" string. These spaces are needed in the output to separate the numbers from the text. Suppose we didn't put the spaces in, and the code looked like this:

 // Problem code std::cout << "Half of" << 64 << "is" << (64 / 2) << "\n"; 

At first glance this code looks perfectly normal. There are spaces around each of the numbers. But these spaces are not inside any string, so they will not be output. The result of this code is:

 Half of64is32 

Omitting needed spaces is a common first-time programming mistake. Remember, only the text inside the quotation marks will be output.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net