Link to home
Start Free TrialLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

String initialization in C++

Hi Experts,

In C, if you want to initialize a char string you would set it to null. But, in C++ string how do I do it?  I think C++ string doesn't terminate on null character.....

char * myStr = "\0";
Avatar of Akumas
Akumas

just declare a std::string object, and it's much safer than c-style char*, little chance to corruption;

initialize:
#include <string>
using std::string;

sttring myStr;//initialized

myStr = "some contant";//assign value

myStr.clear;//clear content in vc7 and above

myStr = "";//clear content in vc6

const char* cStyle = myStr.c_str();//get c style str
When you construct an object of the std::string class from the standard library, it is empty by default, so if that's what you want, you need not do any more to initialize it.  If you want to get rid of the content of a string, you can use the clear function as Akumas showed, except you need parentheses:

myStr.clear();
Avatar of Infinity08
btw, instead of this :

    char * myStr = "\0";

this is sufficient :

    char * myStr = "";

The '\0' character is automatically appended by using "" for initialising.
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial