1

I'm using Visual Studio 2010, and I'm wondering why I'm getting an error.
The error is: cout is undefined

#include<iostream>
#include<stdio.h>
#include<conio.h>



int main()
{
    cout<<"Why am I not working ??";
    printf("My Name is Khan and I'm not a terrorist.");
    return 0;
}
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
Omer Obaid
  • 416
  • 1
  • 6
  • 24

3 Answers3

3

cout is a global object that lives in the std namespace. You have to fully qualify the name:

    std::cout << "Hello";
//  ^^^^^

If you really want to omit the qualification, you could have a using declaration in main() before you use the unqualified name cout (in general, avoid putting using declarations at global namespace scope):

// ...

int main() 
{
    using std::cout;
//  ^^^^^^^^^^^^^^^^

    cout << "Why I'm not working ??";
    // ... 
}  
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
3

cout is in the std namespace. You either need to declare that you are using the std namespace by adding the following to your code (it is generally put just after includes), though this is generally considered bad practise for non-trivial code:

using namespace std;

Or you can qualify cout every time it is used (this is generally preferred):

std::cout << "Hello, World!" << std::endl;
Community
  • 1
  • 1
David Futcher
  • 320
  • 1
  • 7
  • 1
    You don't really *need* to declare that you are using the `std` namespace. It is not necessary to present it as an option, even if you do warn it is a bad one. There's also `using std::cout`. – juanchopanza Jun 11 '13 at 19:47
1

Add the following before int main:

using namespace std;
Sildoreth
  • 1,883
  • 1
  • 25
  • 38
  • Anyone care to qualify their down-vote? My suggestion *will* solve the OP's problem. And given the way they wrote the code in their example, this is the **the** solution they wanted... as opposed to the std::cout solution. – Sildoreth Jun 11 '13 at 19:48
  • It is generally a bad solution. And a better solution would even involve less typing. – juanchopanza Jun 11 '13 at 19:50
  • @juanchopanza Do we just take your word for it that this solution is "bad"? Also, depending on how many occurrences of "cout" the code has, the std::cout solution requires more typing. – Sildoreth Jun 11 '13 at 19:51
  • 1
    +1: using namespace directives are not a bad thing in source files. They are definitely bad in header files, since they get included and pollute other code. – Vittorio Romeo Jun 11 '13 at 19:52
  • No, there are plenty of posts about this on SO. – juanchopanza Jun 11 '13 at 19:52
  • @VittorioRomeo I have seen many, many problems die to placing `using namespace std` in `.cpp` files. If you're going to do that, at least put it in a scope. – juanchopanza Jun 11 '13 at 19:54