Question

I have to use the output of a function of a type const char* and I need to convert it to QString.

Note: inside that function, these are lines of code to return the const char*

char* ClassA::getData() const{
    return const_cast<char *> (_foo.c_str());
}

where _foo is std::string.

I tried to use the following lines of code but always get empty string (actually not empty but contain only the new lines characters and neglect all other characters).

QString foo1 = QString(temp.getData());
QString foo2 = QString::fromLocal8Bit(temp.getData());
QString foo3 = QString(QLatin1String(temp.getData()));
QString foo4 = QString::fromAscii(temp.getData());
QString foo5 = QString::fromUtf8(temp.getData());
Was it helpful?

Solution

The code below should work fine. Your issue is most likely somewhere else. Please do a clean build.

The error will be somewhere else in your more complex code that you have not shared with us. You are probably getting issues with setting _foo incorrectly.

As you noted yourself, you cannot change the interface, but it is better to take a note that in an ideal world, you would not mix std strings with QStrings. You would just use QStrings altogether in your code.

Even if you need to use std or raw char* types for some reason, it is better not to do such a const cast in the code since QString will cope with const strings passed to it.

main.cpp

#include <QString>
#include <QDebug>

class ClassA
{
    public:
        ClassA() { _foo = "Hello World!\n"; }
        ~ClassA() {}

        char* getData() const {
            return const_cast<char *> (_foo.c_str());
        }

    private:
        std::string _foo;
};

int main()
{
    ClassA temp;
    QString myString = QString::fromUtf8(temp.getData());
    qDebug() << "TEST:" << myString;
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Output

TEST: "Hello World!
"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top