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:
- Reason for error
- Fix 1: using namespace
- 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.