Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: ‘string’ has not been declared

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?

like image 750
neuromancer Avatar asked May 23 '10 06:05

neuromancer


3 Answers

string resides in the std namespace, you have to use std::string or introduce it into the scope via using directives or using declarations.

like image 136
Georg Fritzsche Avatar answered Sep 21 '22 06:09

Georg Fritzsche


Use

std::string var;

or

using namespace std;
string var;

String is in a std namespace so you must let your compiler know.

like image 29
KamikazeCZ Avatar answered Sep 25 '22 06:09

KamikazeCZ


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.

like image 27
Adrian Mole Avatar answered Sep 24 '22 06:09

Adrian Mole