In: Computer Science
Whenever I am attempting to write a simple program on C++ I get an error message that reads "cout was not declared in this scope". Literally every time. This has become frustrating because I have even written my code the exact same way as some of my classmates who got theirs to compile and run with no sign of this error at all, and yet min gives this answer. I will leave an example of a code where this error message appeared. Hopefully you can help. Thank you.
ex:
// Example program
#include <iostream>
#include <string>
int main()
{
double mass, velocity,energy;
cout<<"\n enter the objects weight";
cin>>mass;
cout<<"\n enter the objects velocity"
cin>>velocity;
energy=(1.0/2.0)*(mass*velocity)*2;
cout<<"\n mass = "<<mass<<"kg";
cout<<"\n velocity = "<<velocity<<"m/s";
cout<<"\n kinetic energy =
"<<energy<<"kgm/s";
}
Here's the error message:
In function 'int main()': 8:1: error: 'cout' was not declared in this scope 8:1: note: suggested alternative: In file included from 2:0: /usr/include/c++/4.9/iostream:61:18: note: 'std::cout' extern ostream cout; /// Linked to standard output ^ 9:1: error: 'cin' was not declared in this scope 9:1: note: suggested alternative: In file included from 2:0: /usr/include/c++/4.9/iostream:60:18: note: 'std::cin' extern istream cin; /// Linked to standard input ^
Code:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
double mass, velocity,energy;
cout<<"\n enter the objects weight";
cin>>mass;
cout<<"\n enter the objects velocity";
cin>>velocity;
energy=(1.0/2.0)*(mass*velocity)*2;
cout<<"\n mass = "<<mass<<"kg";
cout<<"\n velocity = "<<velocity<<"m/s";
cout<<"\n kinetic energy =
"<<energy<<"kgm/s";
}
The above error can be solved by using namespace std which, is used to define the scope of cout and cin and the context in which defined. In case if something is not declared in the current scope, it will be checked in std, using namespace std.
By using namespace std we can tell the compiler to print or display the cout command directly and cin command to take the input. If we will not tell the compiler to use the namespace std, we have to declared the namespace for every outside object, function, variable, method we call.