tags:

views:

274

answers:

4

Hi, Can anyone please tell me how to convert a C style string (i.e a char* ) to a c++ style string (i.e. std::string) in a C++ program?

Thanks a lot.

+8  A: 

std::string can take a char * as a constructor parameter, and via a number of operators.

char * mystr = "asdf";
std::string mycppstr(mystr);

or for the language lawyers

const char * mystr = "asdf";
std::string mycppstr(mystr);
John Weldon
Thanks a lot...
assassin
I wonder why does everybody responding to this use the flawed (but permitted by the standard) char* type for string literals. All string literals are read-only and thus char const* type should be used. The argument taken by std::string is also char const*.
Tronic
so if I have C type string in a char* variable, then how do I convert it to a C++ style string given that strictly speaking the parameter to the constructor should be char const* type?
assassin
@assassin: you don't have char* at all, but your C type string is a char const*. If it is your code, you can change it, if it is in a library, you cannot.
Rupert Jones
by char* I meant that my C type string is a null terminated character array, pointed to by a char* pointer(say like the char *mystr="asds"; in the example by John above). So given this is std::string mycppstr(mystr); statement gonna give me a valid conversion?
assassin
Yes, it will be valid. Tronic's point is absolutely valid, but not really practically important for the sake of this example.
John Weldon
+2  A: 
char* cstr = //... some allocated C string

std::string str(cstr);

The contents of cstr will be copied to str.

This can be used in operations too like:

std::string concat = somestr + std::string(cstr);

Where somestr is already `std::string``

zaharpopov
Thanks a lot...
assassin
+1  A: 

You can make use of the string class constructor which takes a char* as argument.

char *str = "some c style string";
string obj(str);
codaddict
Thanks a lot...
assassin
A: 

Another way to do the conversion is to call a function which takes a const std::string& as a parameter:

void foo(const std::string& str);

void bar()
{
    char* str= ...

    foo(str);
}

I think its a lot more tidy to do the conversion at a function call boundary.

quamrana
are you saying that foo should be an empty function here and upon calling that function str gets converted to const std::string type?
assassin
quamrana