Lumpi
Lumpi

Reputation: 2821

convert CStdStringW to TCHAR *

I have a piece of code that originally used CString. Since it is not available to VSExpress users I replaced it with a CString "clone" found at: http://www.codeproject.com/KB/string/stdstring.aspx

This clone works just fine but one problem remains when using it:

TCHAR *GetConnectionString(){return m_szConnectionString)}; 

I get the error "no suitable conversion from "CStdStringW" to "TCHAR *" exists" and since string handling not really is my strength I don't know how to resolve this. Ok I know that I probably have to do some kind of type cast but.... The whole piece of code can be found at: Use CString in console app when using VS Express

Well, have a nice day and hopefully someone can help my with.

Regards Lumpi

Upvotes: 1

Views: 928

Answers (2)

Hans Passant
Hans Passant

Reputation: 941635

Once you commit to a non-standard string class, you're stuck with having to use it. You ought to change the return value type:

CStdString GetConnectionString() {
    return m_szConnectionString;
};

The other option is to change the return type from TCHAR to const TCHAR:

const TCHAR* GetConnectionString() {
    return (LPCTSTR)m_szConnectionString;
};

Which isn't a great solution, it will fail miserably when the calling code stores the pointer and the connection string is changed. This is a flaw in the original code too btw.

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

According to the link you posted, CStdString derives from basic_string<TCHAR>. Thus, you can use its c_str() method.

const TCHAR *GetConnectionString()
{
    return m_szConnectionString.c_str();
}

Upvotes: 1

Related Questions