APwrs
04-21-2003, 01:35 AM
I was wondering, how do I convert (or copy) a std::string to an old-style C string? Thank you.
|
Click to See Complete Forum and Search --> : String to C String APwrs 04-21-2003, 01:35 AM I was wondering, how do I convert (or copy) a std::string to an old-style C string? Thank you. vhg119 04-21-2003, 02:04 AM cant you just assing a string object to a char pointer? like string a = "hello"; char* b; b = a; ? no? doesnt a string object have a overloaded assigment operator? APwrs 04-21-2003, 02:12 AM That doesn't quite work. Doing that kicks out the following error message: Sfe.cpp: In function `int main(int, char**)': Sfe.cpp:12: cannot convert `std::string' to `char*' in assignment Thanks for trying, though. infidel 04-21-2003, 04:51 AM Greetings, std::string has a 'c_str()' member function that returns a const char* pointer to the string. If you just need to call a function that takes a const char* parameter you can do it like: #include <string> void function_that_takes_a_c_string(const char* string); int main(int argc, char** argv) { std::string str("The rain in Spain stays mainly in the plane"); fucntion__that_takes_a_c_string(str.c_str()); } void function_that_takes_a_c_string(const char* string) { // If the function needs to modify the string it should copy it first // because it is a const char*. // Note that the changes to the copied string will not be reflected // int the original one! char c_string = new char[strlen(string)]; strncpy(c_string, string, strlen(string)]; ... ... } I'd stay away from C string as much as I can, and use the std::string member functions and operators where possible, it's much safer, cleaner code and sexier! :D Anyway, when necessary you can convert it to a C string like I've shown above. Hope this helps. vhg119 04-21-2003, 03:42 PM does anyone know of a good c++ reference book? i cant seem to find a c++ in a nutshell anywhere busa_blade 04-21-2003, 04:10 PM use the function c_str() method I use the C/C++ Programmer's Reference by Herbert Schlidt It's a pretty good reference APwrs 04-21-2003, 08:40 PM Thank you very much infidel, that was exactly what I needed. I agree with you that it's best to stay way from C strings, but I needed the conversion because I needed to pass a std::string to a system() call, which only takes C strings. I also would like to thank everyone else that replied for their help as well, it is always greatly appreciated. justlinux.com
Copyright Internet.com Inc. All Rights Reserved. |