Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 429
Maciej Ziarko Avatar asked Apr 12 '11 03:04

Maciej Ziarko


Video Answer


2 Answers

See QTextStream::setCodec():

in.setCodec("UTF-8");
like image 190
John Flatness Avatar answered Oct 09 '22 05:10

John Flatness


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 
}
like image 28
Yi Zhao Avatar answered Oct 09 '22 06:10

Yi Zhao