开发者

How to read UTF-8 text from file using Qt?

I have some problems with reading UTF-8 encoded text from file. My version reads only ASCII characters.

#include <QtCore>

int main()
{
    QFile file("s.txt");

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return -1;
    }

    QTextStream in(&file);
    while(!in.atEnd())
    {
        QString line = in.readLine();
        qDebug() << line;
    }
}

s.txt:

jąkać się
ślimak
śnieżyca

output:

开发者_开发百科
"jka si" 
"limak" 
"nieyca"

What should I use?


See QTextStream::setCodec():

in.setCodec("UTF-8");


You shuold do:

QTextStream in(&file);
in.setCodec("UTF-8"); // change the file codec to UTF-8.

while(!in.atEnd())
{
    QString line = in.readLine();
    qDebug() << line.toLocal8Bit(); // convert to locale multi-byte string 
}


I was also having ???? when reading an XML file with QXmlStreamReader. I fixed it by calling this before reading the file:

QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜