1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Rep Power

    Convertign C-String to C++ String

    hi all,

    I need to convert a 'char *' to a C++ 'string'.

    Anybody can help?????
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Rep Power
    It looks like string has a constructor that takes a char*. So this should work:
    char* aCstring = "This is a C-style string.";
    string aCPPstring(aCstring);
    From "EE 462 Object Oriented Programming using C++, Fall 1997, Questions and Answers" at http://www.ece.purdue.edu/~eigenman/EE462/QandA.html :
    Q: What is the difference between char* and string?
    A: char* is a pointer to a character. string (from the standard library) is a class that contains a representation of a sequence of characters plus a range of manipulation functions. Since char* is commonly used in C as a pointer to a sequence of characters, C++ supports this use of "strings" to some degree. For example, class string has a constructor string(char* c_style_string) with which you can create a C++-style string from a char* representation, and there is a function string::c_str() that generates a C-style string from a C++ string.
    Use C++ strings whenever possible. The use of C-style strings should be restricted to the interface to UNIX and library routines. I.e., if a library requires a char* parameter, then you can pass c_str(your_Cpp_string). Or if a library returns a char*, you can construct a C++ string and use this one from then on.

IMN logo majestic logo threadwatch logo seochat tools logo