0

I tried to run hello world in C++ on sublime text 2 on my mac.

I typed

#include "iostream"

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

but it gives me an error

/Users/chiragchaplot/q2.cpp:5:2: error: use of undeclared identifier 'cout'; did you mean 'std::cout'?
        cout<<"Hello World";
        ^~~~
        std::cout
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iostream:50:33: note: 'std::cout' declared here
extern _LIBCPP_FUNC_VIS ostream cout;
                                ^
1 error generated.
[Finished in 0.4s with exit code 1]
MattDMo
  • 100,794
  • 21
  • 241
  • 231
user3393004
  • 1
  • 1
  • 1
  • Side note, but you may want to use `#include ` instead of `#include "iostream"`, since using quotes for system includes works here but may be compiler dependent. – Joachim Isaksson Mar 17 '14 at 09:27

1 Answers1

3

The following methods will solve your problem:


Method 1 : (BAD PRACTICE)

Adding the following line before main function.

using namespace std;

So your code will now become:

#include "iostream"

using namespace std;

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

Method 2 : (GOOD PRACTICE)

You can simply write std::cout instead of cout.

Full code with std::cout

#include "iostream"

int main(){
   std :: cout << "Hello WOrld";
   return (0);
}

This tells the compiler that the cout identifier comes from the std namespace.


Method 2 is better than Method 1. Further reading : Why is "using namespace std" considered bad practice?


For more information on namespaces, check out the following links:

  1. Namespaces Wikipedia
  2. Interesting Q/A @cplusplus.com
  3. Interesting Q/A @devshed.com
  4. Tutorials Point
Community
  • 1
  • 1
Crystal Meth
  • 589
  • 1
  • 4
  • 16
  • ...or, as the compiler message points out, just replace `cout` with `std::cout` to explicitly point out where to find it. – Joachim Isaksson Mar 17 '14 at 09:25
  • The first part of the answer is bad practice and is wrong(you do not need to add that line for the program to work, you simply need to add std:: before cout). See http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – const_ref Mar 17 '14 at 09:29
  • Yes it is a bad practice but a beginner needs to know that as well. – Crystal Meth Mar 17 '14 at 09:30
  • @CrystalMeth Prey tell, Why does a beginner need to be taught bad practice? – const_ref Mar 17 '14 at 09:31
  • @const_ref: He is not supposed to be taught a bad practice, just told that it exists. Anyways, I have included your point in my answer as well. – Crystal Meth Mar 17 '14 at 09:35