string

Started by
5 comments, last by rip-off 15 years, 11 months ago
how do i use string, i include <string.h> or <string> in my cpp file , i have tried both , but when i declare it string s1("test"); the compiler give me an error that string is undeclared variable. Can anyone help?
Advertisement
Use <string>
String resides in the std namespace, so unless you import it, try std::string s("test");
string.h is the c string library the name in C++ is cstring

string is the name from the std::string library

you must prefix std:: before using string
You can also add after you include using namespace std or using std::string if you want to get rid of std::

But don't do this in headers as they will pollute your global namespace.
C++ strings live in the "std" namespace (meaning standard).

You can use "std::" as a prefix to tell the compiler that you are using the string from this namespace, like so:
std::string s1("test");


Alternatively, you can tell the compiler that you are going to be referring to the string inside namespace std like so:
#include <string>using std::string;int main(){   string s1("test");   // ...}


If you are using lots and lots of things from namespace std, you can tell the compiler to check there for everything:
#include <string>using namespace std;int main(){   string s1("test");   // ...}


The last two options should not be used in header files. Once you write a "using" directive, there is no way for files including that header to "un-use" a namespace. This can, in extreme cases, change the meaning of code. It is best to fully qualify symbols in header files for this reason.

Finally, <string.h> is a C header. To use it in C++ write <cstring>. It does not contain std::string.
i have tried , it still give me an error,it tell me that

'std' : a namespace with this name does not exist
'std' : is not a class or namespace name
'string' : undeclared identifier

maybe it cant find the path for string.h or cstring.h, i saw that most people use string.h. do i have to put path so the compiler can find string.h or does he find it automaticaly?
Quote:Original post by totoro9
i have tried , it still give me an error,it tell me that

'std' : a namespace with this name does not exist
'std' : is not a class or namespace name
'string' : undeclared identifier

maybe it cant find the path for string.h or cstring.h, i saw that most people use string.h. do i have to put path so the compiler can find string.h or does he find it automaticaly?
It's not string.h, it's just string:
#include <string>int main(){   std::string s = "foo";   return 0;}
The standard C++ library headers do not have a file extension.

As in my example, and as mentioned by WanMaster, you need to #include <string>. There is no ".h".

This topic is closed to new replies.

Advertisement