Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
In this article, we have explored the reason behind the error "cout is not a member of std" and 2 fixes to resolve this compilation error with C++ code.
Table of contents:
- Reason for the error
- Fix 1: Add header file
- Fix 2: For Microsoft's compiler MSVC
Reason for the error
While compiling a C++ code, you may face the following error:
cout is not a member of std
The reason is that the relevant header files are not provided in the code due to which the compiler is unable to locate the function cout.
Following C++ code which give this error when compiled:
int main() {
std::cout << "data" << std::endl;
return 0;
}
In this article at OpenGenus, we have presented fixes which will resolve this issue.
Fix 1: Add header file
The cout function is available in iostream header file which needs to be included at the beginning of the C++ code.
#include <iostream>
Following is the working code:
#include <iostream>
int main() {
std::cout << "data" << std::endl;
return 0;
}
Fix 2: For Microsoft's compiler MSVC
If you are compiling C++ code on Windows using Microsoft's compiler MSVC (Microsoft Visual Code), include the header file stdafx.h just before iostream.
stdafx.h is a precompiled header file which is used in Microsoft Visual Studio to keep track of files which have been compiled once and not changed following it. This is an optimization in MSVC to reduce compilation time. If it is not added, correct header files are not included in subsequent runs. If iostream header file is not included due to this issue, the compilation error will come.
Include these header files in the same order:
#include "stdafx.h"
#include <iostream>
Following is the working code:
#include "stdafx.h"
#include <iostream>
int main() {
std::cout << "data" << std::endl;
return 0;
}
Compile using MSVC.
With these fixes in this article at OpenGenus, the error must be resolved. Continue with your development.