M Desmond
M Desmond

Reputation: 113

How can I resolve the "cout was not declared in this scope" error?

just a simple program but can anyone point out why this error is occuring, (i am using dev C++ version 5.11)

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

class animal
{
 public :
    void sound();

     void eat() ;

};
void animal::eat()
{
        cout<<"i eat animal food" ; 


}


void animal::sound()
{
        cout<<"i sound like an animal" ;

     }

void main()
{
    animal a ;
    a.sound()
    a.eat()
    getch()
}

the error is coming like this:

In member function 'void animal::eat()':
15  4   C:\Users\chetna\Documents\Untitled1.cpp [Error] 'cout' was not declared in this scope
1   0   C:\Users\chetna\Documents\Untitled1.cpp In file included from C:\Users\chetna\Documents\Untitled1.cpp

Upvotes: 1

Views: 8017

Answers (2)

ebasconp
ebasconp

Reputation: 1638

Please, stop using the old Borland C++ et al.

Use a modern standards compliant C++ compiler (g++, clang, Microsoft Visual Studio) instead.

Do not use conio.h, it is a very old compiler specific library, not a standard one.

Do not use stdio.h it is not a bad library, but it declares several C functions, not C++ ones.

Declare your main function as

int main()

not void main(), because standard C++ needs the main function to return an int (0 for success).

Instead of using cout, use std::cout , because it is an object representing the standard output defined inside the std namespace.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

At least you have to include

#include <iostream>

and

using namespace std;

The name cout is declared in the namespace std. So either use the using directive as shown above or use a qualified name (that is better) like

std::cout<<"i eat animal food" ; 

An alternative approach is to use a using declaration. For example

#include <iostream>

using std::cout;

//...
void animal::eat()
{
        cout<<"i eat animal food" ; 
}

And remove this directive

#include <stdio.h>

Also place semicolons

a.sound();
a.eat();
getch();

Pay attention to that the function main shall be declared like

int main()

Upvotes: 3

Related Questions