Noooobz2016 Noooobz2016 - 3 months ago 14
C++ Question

How do I get the value of text inside of the file using Qt?

The data of my

file.txt
is as below:

Student_ID=0001
Student_Name=joseph
Student_GradeLevel=2


How do I get the value, let say I want to get the
Student_ID
using Qt.
Thanks.

Answer

Take a look at this function, it can be used to find any value you want in your input file, where all lines are in the format you've posted above (key=value). If the key is not found, it returns an empty QString() object.

QString findValueInFile(QString key, QString filename) {
    QFile file(filename);

    if(file.open(QIODevice::ReadOnly)) {
        QTextStream txtStr(&file);
        QStringList fileContent = txtStr.readAll().split('\n');

        for(auto &&line : fileContent) {
            if(line.contains(key)) return line.split(QChar('='))[1];
        }

        file.close();
    }

 return QString(); // not found
}

Now you call it somewhere, e.g.:

qDebug() << findValueInFile("Student_ID", "file.txt");
qDebug() << findValueInFile("Student_Name", "file.txt");

This function can be easily modified if you replace your = sign with other delimiter e.g. => or sth else. However for key=value format there is a special QSettings class (mentioned by sebastian) that can allow you to read those values even easier:

QSettings file("file.txt", QSettings::IniFormat);
qDebug() << file.value("Student_Name").toString(); // et voila!
Comments