如何使用Qt从文件中读取UTF-8文本?

Mac*_*rko 15 c++ qt utf-8 filestream

从文件中读取UTF-8编码文本时遇到一些问题.我的版本只读取ASCII字符.

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

s.txt:

j?ka? si?
?limak
?nie?yca
Run Code Online (Sandbox Code Playgroud)

输出:

"jka si" 
"limak" 
"nieyca"
Run Code Online (Sandbox Code Playgroud)

我该怎么用?

Joh*_*ess 23

QTextStream::setCodec():

in.setCodec("UTF-8");
Run Code Online (Sandbox Code Playgroud)

  • 你怎么修好它的? (11认同)

Yi *_*hao 6

你shuold做:

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 
}
Run Code Online (Sandbox Code Playgroud)