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.
The line usingnamespace 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?