std::wstring to wchar_t *

This is a discussion on std::wstring to wchar_t * within the C++ Programming forums, part of the General Programming Boards category; I have a std::wstring variable and I need to get a wchar_t * from that std::wstring variable. I tried using ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    97

    std::wstring to wchar_t *

    I have a std::wstring variable and I need to get a wchar_t * from that std::wstring variable. I tried using the c_str() method from std::wstring but that returns a const wchar_t * so I get the following error
    Code:
    error C2440: '=' : cannot convert from 'const wchar_t *' to 'wchar_t *'
            Conversion loses qualifiers
    How can I fix that?

  2. #2
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    I think the only way is to use the std::wstring::copy method to copy the contents into a buffer.
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  3. #3
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    >I think the only way is to use the std::wstring::copy method to copy the contents into a buffer.

    Or you could just re-cast it:

    C style:

    wchart* wc = (wchart*)s.c_str();

    or C++ style:

    wchart* wc = const_cast<wchar_t*>( s.c_str() );

    Be sure you understand why you are removing the const (ie. don't then attempt to modify the string contents). It is there for a reason--because the contents of the string pointer is not meant to be modified.
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

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