c_str()

This is a discussion on c_str() within the C++ Programming forums, part of the General Programming Boards category; Hi Just reading up on c_str() and notice that it returns a pointer to a c string. So, for example, ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    329

    c_str()

    Hi

    Just reading up on c_str() and notice that it returns a pointer to a c string.

    So, for example, if I want to use this to obtain a string from a stringstream, would I use :
    const char* p = ss.c_str(); or
    string p = ss.c_Str(); ?

    Both work, however because c_str() returns a pointer should I be using the former solution?

    Thanks.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,677
    The two lines have different effects, so the right choice depends on what you want to do with the result.

    If you need a C-style string (or a pointer to the first character of a C-style string) the first is the way to go. Note that p should not then be used in any way after any subsequent operation that changes ss.

    If you need p to be a C++ string (std::string) copy of ss the second has that net effect (assuming the contents of ss are equivalent to a C-style string) but is more effectively done without a temporary C-style string as;
    Code:
       string p = ss;
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Quote Originally Posted by grumpy View Post
    The two lines have different effects, so the right choice depends on what you want to do.

    If you need a C-style string, the first is the way to go. Note that p should not then be used in any way after any subsequent operation that changes ss.

    If you need p to be a C++ string (std::string) copy of ss the second has that net effect (assuming the contents of ss are equivalent to a C-style string) but is more effectively done without a temporary C-style string as;
    Code:
       string p = ss;
    Right, thanks, I understand now.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21