qtstdstringqstringwchar

Strange behavior with QString


Here's my code:

#include <QCoreApplication>
#include <QTextStream>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream out(stdout);

    QString filename = "F:/temp/йцук.tx";

    out << filename << endl;

    const wchar_t* fn_wch = filename.toStdWString().c_str();

    std::wcout << filename.toStdWString().c_str() << std::endl;   //1
    std::wcout << fn_wch << std::endl;                            //2

    return a.exec();
}

The problem is rows "1" and "2" outputs different strings. But aren't they should be the same? Because I assigned fn_wch to filename.toStdWString().c_str() before that.

UPD0:

I've changed the code to prevent accessing to data of the destroyed wstring:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream out(stdout);

    QString filename = "F:/temp/йцук.tx";

    out << filename << endl;

    auto wstr = filename.toStdWString();

    auto wchar = wstr.c_str();

    std::wcout << wchar << std::endl; //1

    std::wcout << wchar << std::endl; //2

    std::wcout << wstr; //3

    return a.exec();
}

But problem remains the same: row 1 outputs data, but 2 and 3 doesn't.


Solution

  • int main(int argc, char *argv[])
    {
        setlocale(LC_ALL, "russian");
        QCoreApplication a(argc, argv);
        QTextStream out(stdout);
    
        QString filename = "F:/temp/йцук.tx";
    
        out << filename << endl;
    
        auto wstr = filename.toStdWString();
    
        //auto wchar = wstr.c_str();
        wchar_t wchar[wstr.size()];
        wcscpy(wchar, wstr.c_str());
    
        std::wcout << wchar << std::endl; //1
    
        std::wcout << wchar << std::endl; //2
    
        std::wcout << wstr; //3
    
        return a.exec();
    }
    

    It works. Pointer in c_str() is destryed, so you need to copy data.