How to convert QString to LPCSTR (Unicode)

13,493

Solution 1

I guess:

QString str("ddddd");
LPCSTR lstr = str.toStdString().c_str();

Solution 2

QString can always hold Unicode; LPCSTR is never Unicode. This means that you do have to consider what to do with the characters that won't fit. This isn't a "which method to use" question, but a design question.

It's quite possible that in your specific case, you absolutely know that the QString only contaisn characters from your local "ANSI" codepage (also known as ACP). In that case, the correct function is QString::toLocal8Bit ().

Alternatively, you might know that the QString only contains characters from Latin1 (ISO 8859-1). In that case, the correct function is QString::toLatin1().

You could try to call QString::toUtf8(). This will always produce a valid byte array, even if the QString contained all Unicode characters. However, formally you can't point a LPCSTR to it: UTF-8 is not a valid ACP codepage. And presumably, you want this LPCSTR to pass to another function outside your control. It's likely that function won't expect UTF-8. If it expected Unicode at all, it would take a LPCWSTR.

Share:
13,493
Admin
Author by

Admin

Updated on July 01, 2022

Comments

  • Admin
    Admin almost 2 years

    how can I convert QString to LPCSTR ?

    How do I do it when #ifdef UNICODE is defined and when it isn't ?

    Thanks very much :)