(Elsewhere in the thread the book was mentioned as _C++ Programming in
Easy Steps_ (4th ed.) by Mike McGrath)
I found the page you're looking at, page 12, in Amazon's "Look inside
this book" feature. It does indeed say to type that in, but you'll
note that above that, it ALSO says to type in
#include <iostream>
using namespace std;
As others have already observed, typing in the EXACT code given in the
book without any typos or omissions is crucially important. (Not only
in C++, but for any programming language.)
Nitpick: Actually, you probably need to type in
std::cout << "Hello World" << std::endl;
to see any output -- the 'std::endl' is what actually tells the
program to dump the text to the screen. It *may* produce output
without the endl, depending on your platform, but I definitely
wouldn't count on it.
Well, the shallowest explanation is that you can't do that because you
didn't type in "using namespace std;" that the book told you to put in
above that
As for the reasons behind this: You may need to read further in the
book before fully understanding this, but here goes.
Most C++ standard library objects, including cout and endl, are in a
namespace provided by the standard library headers that is called
"std", rather than the "global namespace". Unless you tell the
compiler to use a particular namespace, which is what the "using
namespace std;" does, it only looks up UNqualified object names in the
global namespace. (Or the current scope, or its parent scope, etc.,
but you don't have to think about that quite yet.)
A "qualified" name is something like "std::cout". If you've
#include'd the necessary headers, using a qualified name will always
work, whether you've said to use the std namespace or not.
By the way, "using namespace std;" is seldom desirable in real-world
code since it pulls in EVERYTHING in the namespace (that's visible
from current #include directives). It is commonly used in pedagogical
settings for brevity. But one would usually prefer
using std::cout;
using std::endl;
... this allows you to use "cout" and "endl" without the std::
qualification, but without "polluting" your namespace with all the
other functions, classes, etc. in std. If the Standard Library
objects were in the global namespace, this selective namespace
importation wouldn't be possible.
Hope this helps,
- Kevin B. McCarty