Using std:: infront of cout/cin/etc. when they belong to the iostream library?

Sorry if this is a noob question but I just started reading C++ Primer and in their example code they use the standard namespace in front of cin/cout/endl but why is that necessary? I thought they belonged to the iostream library so why do you need to put std:: infront of those objects? I'm a complete noob to C++ so I'm trying to get a grasp on namespaces/libraries.

closed account (2b5z8vqX)
why do you need to put std:: infront of those objects?

The entity being referenced would not be found without qualification in most cases.
Last edited on
Hello Rafael Maldonado!

std is a namespace. It is like an area code for a phone number. So using std::cout for example is like calling a number in a certain area code.

Also, if you do this:

1
2
3
4
5
6
7
8
9
#include <iostream>

using namespace std;

int main()
{
       cout << "Hello World!";
       return 0;
}


The line using namespace std;
is like making std the local area code. So whenever you refer to something in the std namespace, the compiler knows what you are talking about.

Another way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using std::cout;
using std::cin;

int main()
{
      cout << "Hello World!" << std::endl; //I did not specify endl with cout and cin, so I have to specify the namespace for endl
      int number = 0;
      cout << "Enter a number: ";
      cin >> number; //The compiler knows where cin is, because of the above statements.
      cout << "You entered " << number ". \n";
      return 0;
}


using std::cout; and using std::cin; made cout and cin specifically known to the compiler. So when I tried to use endl, I had to specify the namespace. Get it?
Last edited on
Topic archived. No new replies allowed.