Read word by word from a text file in Qt4

后端 未结 1 1291
闹比i
闹比i 2021-01-28 10:57

I want to read a text file word by word in Qt4 (to which I am very new to be honest), I want and write in another file one word per line. I could do this in C++ without any prob

相关标签:
1条回答
  • 2021-01-28 11:21

    You could combine QString::split and QStringList::join to achieve your aim:

    #include <QFile>
    #include <QStringList>
    #include <QCoreApplication>
    #include <QTextStream>
    
    int main()
    {
        QFile ifile("in.txt");
        ifile.open(QIODevice::ReadOnly | QIODevice::Text);
    
        // read whole content
        QString content = ifile.readAll();
        // extract words
        QStringList list = content.split(" ");
    
        ifile.close();
    
        QFile ofile("out.txt");
        ofile.open(QIODevice::WriteOnly | QIODevice::Text);
    
        QTextStream out(&ofile);
    
        // join QStringList by "\n" to write each single word in an own line
        out << list.join("\n");
    
        ofile.close(); 
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题