87

I have a C++ program:

test.cpp

#include<iostream>

int main()
{
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;    //this causes an error, cout was not declared in this scope
    return 0;
}

I get the error:

'cout' was not declared in this scope

Why?

Grandtour
  • 1,127
  • 1
  • 11
  • 28

2 Answers2

138

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

displayName
  • 13,888
  • 8
  • 60
  • 75
zbigniewcebula
  • 1,610
  • 2
  • 12
  • 9
  • 17
    Such [bad advice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – juanchopanza Dec 15 '15 at 22:44
  • 5
    I know, I made that answer 2 years ago, but now I know it is good enough for beginner, because it is stupid and hard to explain novice programmer what namespace is. – zbigniewcebula Dec 17 '15 at 00:16
  • 8
    I disagree. This is particularly bad for beginners because they can't see the implications. – juanchopanza Dec 17 '15 at 00:26
  • 3
    I agree with @juanchopanza here. It is much easier to start with a solid foundation and explain what everything does so that they don't have to relearn the concepts of something that they thought they already have taken care of – Crutchcorn Feb 04 '16 at 03:40
  • 1
    tl;dr "using std::cout;" – NicoKowe Nov 30 '21 at 21:10
44

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451