Noooobz2016 Noooobz2016 - 8 months ago 34
C++ Question

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

The data of my

is as below:


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


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( {
        QTextStream txtStr(&file);
        QStringList fileContent = txtStr.readAll().split('\n');

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


 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!