Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to Read Value from a text file and Iterate?



  • Hi all,

    I have a .txt file with 6 random integer as following layout:

    52
    241
    40
    180
    7
    120

    I used the following code to read from the text file.
    @void Dialog::loadInitValue()
    {
    QString list;
    QString path="/mnt/rd/hsv.txt";
    QFile valueHSV(path);
    if(!valueHSV.open(QIODevice::ReadOnly|QIODevice::Text))
    {
    qDebug() << "cannot open file for reading"<<endl;
    return;
    }

    QTextStream hsv(&valueHSV);
    while(!hsv.atEnd())
    {
        list.append(hsv.readLine());
        if(list.isNull())
            break;
         qDebug()<<list;
    }
    foreach(QString str, list)
    {
        int value = str.toInt();
        qDebug()<<value;
    }
    
    return;
    

    }@

    for "list", i will get:
    "52"
    "241"
    "40"
    "180"
    "7"
    "120"

    for "value", i will get:
    5
    2
    2
    4
    1
    4
    0
    1
    8
    0
    7
    1
    2
    0

    I would like to store each of the value into different variables.
    How could i achieve this?



  • hii

    • Line 3 : -QString list;
      Update by QStringList list;

    • Line 16: -list.isNull());
      Update by list.isEmpty();

    hope it helps


  • Qt Champions 2017

    You can make it more simple if the file format given by is the only format.

    @ QString path="hsv.txt";
    QFile valueHSV(path);
    if(!valueHSV.open(QIODevice::ReadOnly|QIODevice::Text))
    {
    qDebug() << "cannot open file for reading"<<endl;
    return 1;
    }

    while(!valueHSV.atEnd()){
       QString val =  valueHSV.readLine();
       qDebug() << val.toInt();
    }@


  • Iterating through a QStringList should best be done with a const_iter variable.
    Or simply take the first element, and send via debug, but then you loose the data.


Log in to reply