The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

Andrey Bushman picture Andrey Bushman · Nov 3, 2012 · Viewed 102k times · Source

I learn C++ and COM through the books. In the IDE MS Visual Studio 2012 I have created new empty C++ project, and added some existing files to it. My CPP file contains #include<iostream> row, but in editor I got such messages:

Error: identifier "cout" is undefined

end

Error: identifier "endl" is undefined

Screen:

enter image description here

Why it happens?

Answer

juanchopanza picture juanchopanza · Nov 3, 2012

You need to specify the std:: namespace:

std::cout << .... << std::endl;;

Alternatively, you can use a using directive:

using std::cout;
using std::endl;

cout << .... << endl;

I should add that you should avoid these using directives in headers, since code including these will also have the symbols brought into the global namespace. Restrict using directives to small scopes, for example

#include <iostream>

inline void foo()
{
  using std::cout;
  using std::endl;
  cout << "Hello world" << endl;
}

Here, the using directive only applies to the scope of foo().