Cout was not declared in this scope ошибка

Asked

Viewed
505k times

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's user avatar

Grandtour

1,1271 gold badge11 silver badges28 bronze badges

asked Mar 3, 2013 at 12:46

2

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's user avatar

displayName

13.9k8 gold badges60 silver badges75 bronze badges

answered Mar 3, 2013 at 14:08

zbigniewcebula's user avatar

zbigniewcebulazbigniewcebula

1,6102 gold badges12 silver badges9 bronze badges

5

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

answered Mar 3, 2013 at 12:47

Andy Prowl's user avatar

Andy ProwlAndy Prowl

124k23 gold badges387 silver badges451 bronze badges

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have explored the reason behind the compilation error «cout was not declared in this scope» and how to fix it.

Table of contents:

  1. Reason for error
  2. Fix 1: using namespace
  3. Fix 2: Scope resolution operator

The quick fix is to add the following line in your C++ code just after the include statements:

using namespace std;

Reason for error

While compiling a C++ code, you may get this compilation error:

'cout' was not declared in this scope

If you compile this C++ code, you will get this compilation error:

#include <iostream>

int main() {
    std::cout << "data" << std::endl;
    return 0;
}

Fix 1: using namespace

The easiest fix is to add the code line «using namespace std;» at the top of the code after include statements. This tells the compiler that functions like cout and endl are under the namespace std.

using namespace std;

Following is the complete working C++ code:

#include <iostream>
using namespace std;

int main() {
    cout << "data" << endl;
    return 0;
}

Fix 2: Scope resolution operator

An alternative fix is to add the namespace std with cout and endl using the scope resolution operator. Following are the required changes:

  • Replace «cout» with «std::cout»
  • Replace «endl» with «std::endl»

Following is the complete working C++ code:

#include <iostream>

int main() {
    std::cout << "data" << std::endl;
    return 0;
}

With the fixes in this article at OpenGenus, you must have solved this issue. Continue with your C++ development.

I realize that there are several duplicates like this but none of them have worked for me so far.
I am trying to compile a C++ very simple program on Ubuntu using g++ but it is giving me scope errors.

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello world";
}

This gives me this error:

sudo g++ -v test.c
test.c: In function ‘int main()’:
test.c:7:3: error: ‘cout’ was not declared in this scope

I also tried defining the scope as many other posts say, but that also didn’t work, but gave me a different error:

#include <iostream>

int main()
{
  std::cout << "Hello world";
}

Gives error:

test.c: In function ‘int main()’:
test.c:6:3: error: ‘cout’ is not a member of ‘std’

Most of the suggestions online suggest «using namespace std;», «#include » and «std::cout».
So I tried all 3 together, still no luck :(

#include <iostream>
using namespace std;

int main()
{
  std::cout << "Hello world";
}

gives error:

test.c: In function ‘int main()’:
test.c:7:3: error: ‘cout’ is not a member of ‘std’

I have gone through several forums online but none of them seem to work for me :(

This is a part of a bigger issue because of which one of my linux make doesn’t work.

Btw, I am using g++ and not gcc as a few posts messed up.


EDIT 1:

I changed the name to .cpp, and execute without sudo. Here is the verbose output:

pranoy@pranoyubuntu1210:~/Desktop/SIP/SIPp/sipp-3.3$ g++ -v test.cpp -o test
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.7/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.7.2-2ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1) 
COLLECT_GCC_OPTIONS='-v' '-o' 'test' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 /usr/lib/gcc/x86_64-linux-gnu/4.7/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE test.cpp -quiet -dumpbase test.cpp -mtune=generic -march=x86-64 -auxbase test -version -fstack-protector -o /tmp/cczzibvL.s
GNU C++ (Ubuntu/Linaro 4.7.2-2ubuntu1) version 4.7.2 (x86_64-linux-gnu)
    compiled by GNU C version 4.7.2, GMP version 5.0.2, MPFR version 3.1.0-p3, MPC version 0.9
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../x86_64-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/c++/4.7
 /usr/include/c++/4.7/x86_64-linux-gnu
 /usr/include/c++/4.7/backward
 /usr/lib/gcc/x86_64-linux-gnu/4.7/include
 /usr/local/include
 /usr/lib/gcc/x86_64-linux-gnu/4.7/include-fixed
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
GNU C++ (Ubuntu/Linaro 4.7.2-2ubuntu1) version 4.7.2 (x86_64-linux-gnu)
    compiled by GNU C version 4.7.2, GMP version 5.0.2, MPFR version 3.1.0-p3, MPC version 0.9
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 521527ea42f0901bf839bcaad0cb13e6
test.cpp: In function ‘int main()’:
test.cpp:5:3: error: ‘cout’ is not a member of ‘std’

  • Forum
  • Beginners
  • error: ‘cout’ was not declared in this s

error: ‘cout’ was not declared in this scope

I am trying to use a program to calculate BMI with modules. I have started with the following code (could be very wrong but I am a beginner). Can someone help me understand why I am getting an error of error: ‘cout’ was not declared in this scope?

#include <iostream>
double height, weight;
double bmiCal (double height, double weight);

void BMIcalc()

{
cout << «This program will calculate BMI» << endl;

std::cout << "This program will calculate BMI\n";

cout belongs to the std namespace, so one has to communicate that to the compiler. I put \n rather than endl because that can be a little inefficient — it flushes the buffer every time.

Please always use code tags: http://www.cplusplus.com/articles/z13hAqkS/

Hi ositamay11,

My first thought is based on the code you posted is that

should be

Or you could start your code

1
2
3
4
5
6
#include <iostream>

using namespace std;

double height, weight;
double bmiCal (double height, double weight);

That is the quick answer. I know that the

dose save some typing. And I know there is a better explanation of how it all works maybe some one else can explain it better.

using namespace std; 0r
std::cout《"blah blah"
Either of then would work. The first one is not considered a good practice as apparentely it makes program slower but at this level, it is insignificant.

The problem with using namespace std; is that it can cause naming conflicts (it brings into the global namespace all of std that is in whatever header files one has included), and undermines the whole purpose of having namespaces — which is to help prevent naming conflicts. There are lots of ordinary English words that exist in std, such as left, right which are both defined in iostream. So if one had a variable or function named left, there is a conflict with std::left. It’s worse the more includes one has — especially with the algorithm header file.

It might seem easy to have using namespace std; now, but it will bite you one day.

It is possible to do this:

1
2
3
using std::cout;
using std::cin;
using std::endl;

but that gets tiresome as well, it’s easy to accumulate lots of them. The easiest thing to do in the end is to get put std:: before every std thing. That is what all the experienced coders do, so one might as well get ahead of the game now :+)

Also, using std:: is explicit — std::copy means just that, not boost::copy or some other copy from a different library.

Ideally one should put their own code into it’s own namespaces.

Topic archived. No new replies allowed.


Recommended Answers

post one of the files that has the errors, especially the top of the *.cpp file where you have all the includes etc. The problem is most likely missing something like this:

#include <iostream>
using std::cout;

or this

#include <iostream>
using  namespace std; // …

Jump to Post

what would happen if you change you include section to look like this

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <assert.h>

using namespace std;

Jump to Post

you know, this post seems suspicious. It looks like( at lest to me) that you are
trying to get someone else’s code, who wrote it a while back, to compile so you can use
it either for h.w or for some school related stuff? If you don’t get what graphs …

Jump to Post

All 10 Replies

Member Avatar for Ancient Dragon


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster



post one of the files that has the errors, especially the top of the *.cpp file where you have all the includes etc. The problem is most likely missing something like this:

#include <iostream>
using std::cout;

or this

#include <iostream>
using  namespace std; // Not recommended

or like this:

#include <iostream>

int main()
{
   std::cout << "Hello World\n";
}

Edited

by Ancient Dragon because:

n/a

Member Avatar for KAY111


/********************************************************************/
/*                                                                  */
/*  parse (...) :                                                   */
/*       1. Reads the graph problem in extended DIMACS format.      */
/*       2. Prepares internal data representation                   */
/*                                                                  */
/*  Requires Routines:                                              */
/*       1. readProblemLine                                         */
/*       2. readNodeDescription                                     */
/*       3. readArcDescription                                      */
/*                                                                  */
/********************************************************************/
       
// Files to be included:
#include <iostream.h>
using std::cout;
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

//#ifdef NO_ERROR_HANDLING
//#define throw(string)  {cerr << string << "\n"; exit(1);}
//#define try
//#endif

inline void swap(arc *e1, arc *e2)
{
  arc temp = *e1;
  *e1 = *e2;
  *e2 = temp;
#ifdef REVERSE_POINTER
  if (e1->reverseArc() != e1)
    {
      e1->reverseArc()->setReverse(e1);
      e2->reverseArc()->setReverse(e2);
    }
  else 
    {
      e1->setReverse(e2);
      e2->setReverse(e1);
    }
#endif
}

void parse()
{
  long   *arc_tail=NULL;          // Internal Array: tails of the arcs
  long   *arc_first=NULL;         /* Internal Array for holding:
                                     - node degree
                                     - position of the first outgoing arc */
  long   tail;                    // Tail of current arc

  long   arc_num;
  long   arc_new_num;
//  DistType   max_cost = 0;

  arc    *arc_current=NULL;       // Pointer to the arc structure
  arc    *arc_new;
  node   *v; 

  long    no_lines=0;             // # of current input line
  long    no_plines=0;            // # of problem-lines
  long    no_nlines=0;            // # of node(source)-lines
  long    no_alines=0;            // # of arc-lines

  char    input_line[MAXLINE];    // For reading input line

/* The main loop:
        -  reads the line of the input,
        -  analises its type,
        -  checks correctness of parameters,
        -  puts data to the arrays,
        -  does service functions
*/
  try{
    while ( gets ( input_line ) != NULL ) {
      no_lines ++;

      switch (input_line[0]) 
	{
	case 'c':                       // Skip lines with comments
	case '\n':                      // Skip empty lines   
	case '\0':                      // Skip empty lines at the end of file
	case 't':                       // Name of the problem
	  break;
	    
	case 'p':                       // Problem description     
	  if ( no_plines > 0 ) throw("more than one problem line");                         //CHANGE MADE BY AMULYA YADAV.....JUST TO CHECK 
	  no_plines = 1;
   
	  readProblemLine(G,input_line);

	  arc_tail = new long[G.numArcs()]; 
	  arc_first= new long[G.numNodes()+1];
	  for (long i=0; i<G.numNodes()+1; i++) arc_first[i]=0;

	  if ( arc_first == NULL || arc_tail == NULL )
	    throw("can't obtain enough memory to solve this problem");
		     
	  arc_current = G.firstArc();	    // Setting pointer to the current arc
	  break;
	
	case 'n':		               // Node description
	  if ( no_plines == 0 ) throw("problem description must come first");
	  if ( no_nlines > MAX_NODE_LINES) throw("too many nodes in the input");

	  no_nlines++;   
	  readNodeDescription(G,input_line);
	  break;

	
	case 'a':                    // Arc Description
	  if ( no_nlines < MIN_NODE_LINES )  throw("too few nodes lines"); 	    
	  if ( no_alines >= G.numArcs() )  throw("too many arcs input");
		
	  tail = readArcDescription(G,input_line,arc_current);
	  arc_first[tail + 1] ++; /* no of arcs outgoing from tail
                                           is stored in arc_first[tail+1] */

	  // Storing Information About The Arc
	  arc_tail[no_alines] = tail;

#ifdef REVERSE_ARCS  //Add reverse arc as well
	  tail = G.index(arc_current->head());
	  arc_current++;
	  no_alines++;
	  arc_first[tail + 1] ++;
	  arc_tail[no_alines] = tail;
#endif
	  no_alines ++;
	  arc_current ++;
	  break;

	default:
	  throw("unknown line type in the input");
	  break;
	  
	} // End of switch
    }     // End of input loop

/* ----- all is red  or  error while reading ----- */ 

    if ( feof (stdin) == 0 ) throw("reading error");

    if ( no_lines == 0 ) throw("input file is empty");

//if ( no_alines < G.numArcs() ) // Not enough arcs
//  parserError(EN19,no_lines);

#ifdef ARTIFICIAL_SOURCE
    //    G.setSource(SOURCE);

    forallNodes(v,G)  {
      if (!connectedToSource(v)) continue;

      createSourceArc(arc_current,v);  // Create reverse arc at same time
      arc_current++;

      tail =  G.getSource()->index();
      arc_first[tail + 1] ++;
      arc_tail[no_alines] = tail;
      no_alines++;
#ifdef REVERSE_ARCS      
      arc_current++;
      tail =  G.index(v);
      arc_first[tail + 1] ++;
      arc_tail[no_alines] = tail;
      no_alines++;
#endif // REVERSE_ARCS

    }
#endif // ARTIFICIAL_SOURCE

#ifdef ARTIFICIAL_SINK  
    //    G.setSink(SINK);

    forallNodes(v,G)  {
      if (!connectedToSink(v)) continue;

      createSinkArc(arc_current,v);  // Create reverse arc at same time
      arc_current++;

      tail =  G.index(v);
      arc_first[tail + 1] ++;
      arc_tail[no_alines] = tail;
      no_alines++;
#ifdef REVERSE_ARCS      
      arc_current++;
      tail =  G.getSink()->index();
      arc_first[tail + 1] ++;
      arc_tail[no_alines] = tail;
      no_alines++;
#endif // REVERSE_ARCS

    }
#endif // ARTIFICIAL_SINK

    forallNodes(v,G) {
      long indx;
      indx = G.index(v);
      if (v !=  G.firstNode())   arc_first[indx] += arc_first[indx-1];
      v->initAdjList( G.arc_i(arc_first[indx]) );
    }
    // init. sentinel
    G.node_i(G.numNodes())->initAdjList(G.arc_i(G.numArcs()));

    /*
    // setup first arcs, including sentinel node
    long indx, sum;
    sum = 0;
    for (indx = 0; indx <= G.numNodes(); indx++)
      {
	sum+=arc_first[indx];
	v = G.node_i(indx);
	v->initAdjList(G.arc_i(sum));
      }
      */
/********** ordering arcs - linear time algorithm ***********/

/* before below loop arc_first[i+1] is the number of arcs outgoing from i;
   after this loop arc_first[i] is the position of the first 
   outgoing from node i arcs after they would be ordered;
   this value is transformed to pointer and written to node.first[i]
   */


    forallNodes(v,G) {
      long indx;
      indx = G.index(v);
      // AVG      last =  G.index(v->lastOutArc());
                             /* arcs outgoing from i must be cited    
                              from position arc_first[i] to the position
                              equal to initial value of arc_first[i+1]-1  */
      arc *e;

      e = G.arc_i(arc_first[indx]);
      forallRemainingOutArcs(e,v) { 
	arc_num = G.index(e);
	tail = arc_tail[arc_num];
          /* the arc no  arc_num  is not in place because arc cited here
             must go out from indx;
             we'll put it to its place and continue this process
             until an arc in this position would go out from indx */
	while ( tail != indx ) {
	  arc_new_num  = arc_first[tail];
	  arc_new      = G.arc_i(arc_new_num);
	  swap(arc_new,e);
	  arc_tail[arc_num] = arc_tail[arc_new_num];

	  // We Increase arc_first[tail] but Label Previous Position

	  arc_tail[arc_new_num] = tail;
	  arc_first[tail] ++ ;
	  
	  tail = arc_tail[arc_num];
	}
      }
      /* all arcs outgoing from  v  are in place */
    }       

// -----------------------  Arcs Are Ordered  ------------------------- */

// Assigning Output Values

#ifdef SHORTEST_PATH
if ( G.getSource()->adjListIsEmpty() ) throw("no arc out of source");
#endif
   }
#ifndef NO_ERROR_HANDLING
catch(char *str) {
  cerr << input_line;
  cerr << "\nLine " << no_lines << " of input - " << str << "\n";
  abort();
}
#endif

// Free Internal Memory 
  delete arc_first ; 
  delete arc_tail ;

/* ---------------------------------- */

}

/* --------------------   end of parser  -------------------*/

This is the code that is problematic.Actually ,the code which I have has many files and this is one of them.It has a make file and that is what I try to run by using make install.The errors that show up are:
In file included from lds_run.cc:20:
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:99: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:105: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:106: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:114: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:115: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:136: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:144: error: ‘cout’ was not declared in this scope
/media/HCL_DISK3/bim-1.0/common/base_parser.cc:146: error: ‘cout’ was not declared in this scope


These are just a part of the errors that I’m getting.If you still feel you’re not sure what the problem is.you can go this link http://avglab.com/andrew/soft.html and download the the zip file named BIM…that’s the code I’m trying to run.

Any help will be appreciated.
Thanks,anyway.

Member Avatar for KAY111


I tried changing the iostream.h to iostream also.I’ve tried out all variations that you told me about.But none of them has worked.

Thanks

Member Avatar for NathanOliver


what would happen if you change you include section to look like this

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <assert.h>

using namespace std;

Member Avatar for KAY111


Enormous number of errors pop up in wchar2.h and wchar.h which are standard C++ library files and this should definitely not happen.A sample of the errors is as follows:

/usr/include/bits/wchar2.h: In function ‘wchar_t* __wmemcpy_alias(wchar_t*, const wchar_t*, size_t)’:
/usr/include/bits/wchar2.h:28: error: ‘cout’ was not declared in this scope
/usr/include/bits/wchar2.h:28: error: expected primary-expression before ‘<<’ token
/usr/include/bits/wchar2.h: In function ‘wchar_t* __wmemcpy_chk_warn(wchar_t*, const wchar_t*, size_t, size_t)’:
/usr/include/bits/wchar2.h:32: error: ‘cout’ was not declared in this scope
/usr/include/bits/wchar2.h:32: error: expected primary-expression before ‘<<’ token
/usr/include/bits/wchar2.h: At global scope:
/usr/include/bits/wchar2.h:36: error: expected ‘;’ before ‘__attribute__’
/usr/include/bits/wchar2.h:36: error: declaration does not declare anything
/usr/include/bits/wchar2.h: In function ‘wchar_t* wmemcpy(wchar_t*, const wchar_t*, size_t)’:
/usr/include/bits/wchar2.h:40: error: redefinition of ‘wchar_t* wmemcpy(wchar_t*, const wchar_t*, size_t)’
/usr/include/wchar.h:327: error: ‘wchar_t* wmemcpy(wchar_t*, const wchar_t*, size_t)’ previously defined here
/usr/include/bits/wchar2.h:40: error: ‘cout’ was not declared in this scope
/usr/include/bits/wchar2.h:40: error: expected primary-expression before ‘<<’ token

Member Avatar for KAY111


Nathan and Ancient Dragon,any help shall be appreciated………..ive already given u the link in case u want a complete understanding of the problem……
Thanks

Member Avatar for mrnutty


you know, this post seems suspicious. It looks like( at lest to me) that you are
trying to get someone else’s code, who wrote it a while back, to compile so you can use
it either for h.w or for some school related stuff? If you don’t get what graphs are
then go study more theory and ask specific questions, otherwise good luck cheating.

———————
PS: forgive if I was wrong.

Member Avatar for KAY111


Dont be bitter if you dont have an answer to the questions asked.And I dont think you are important enough to tell you what am I doing with this code?……….and you know what,I’d even suggest a course in etiquettes for u………….

Member Avatar for Ancient Dragon


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster



what compiler are you using anyway? I tried to compile it with vc++ 2010 express and had no problems using

#include <iostream>
using std::cout;
// etc. etc

The code you posted 6 hours ago contains a lot of other problems than just the one you have been complaining about, most likely because you have failed to include other critical header files. You will never get a clean compile without those header files.

Member Avatar for KAY111


Hi Ancient Dragon,
I am using GNU g++ compiler.
and yup,there are a lot of dependencies in between a lot of files so I dont compile them one by one. The scientist who had written this code had written a makefile and i use that to compile and generate the binaries.

I dont think i can post all the files here .there are more than 100 files in the source code. But if you want to get a good look, I have put in the link where you’ll find the code.

Thanks for replying.


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Понравилась статья? Поделить с друзьями:
  • Coo 689 ошибка скания
  • Cout is ambiguous c ошибка
  • Convotherm ошибка e58
  • Converting circular structure to json ошибка
  • Converter exe ошибка