In my header file I'm getting the
error: ‘string’ has not been declared
error but at the top of the file I have #include <string>
, so how can I be getting this error?
string
resides in the std
namespace, you have to use std::string
or introduce it into the scope via using directives or using declarations.
Use
std::string var;
or
using namespace std;
string var;
String is in a std namespace so you must let your compiler know.
Most of the classes and class templates, and instances of those classes, defined by the Standard Library (like string
and cout
) are declared in the std::
namespace, not in the global namespace. So, whenever you want to use (say) string
, the class is actually std::string
.
You can add that namespace prefix explicitly every time you use such a class, but that can become tedious. In order to help, you can add using
declarations for those classes you use frequently.
So, in your case, you could add lines like the following, generally somewhere shortly after the corresponding #include
lines:
#include <string>
#include <iostream>
using std::string;
using std::cout; // Added as illustrative examples of other
using std::endl; // ... elements of the Standard Library
Or, if you have a compiler that supports the C++17 Standard (or later), you can put more than one class in the same statement:
using std::string, std::cout, std::endl; // C++17 or later
But, beware of using the generic, "cover-all" using namespace std;
directive (even though that is actually valid C++ syntax). See: Why is "using namespace std;" considered bad practice?
For a more general introduction to, and overview of, the Standard Template Library (now, more correctly known as the C++ Standard Library), see the tag-Wiki for the stl tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With