B
B
Burgul2014-05-23 19:57:39
C++ / C#
Burgul, 2014-05-23 19:57:39

QT QFile C++ How to read numbers from a file into an array?

Good day.
There is a file: test.txt.

1	1	1	1	1	1
1	1	1	1	1	1
1	1	1	1	1	1
1	1	1	1	1	0
1	0	0	0	0	0
0	0	0	0	0	1
0	1	1	1	1	1
1	1	1	1	1	1

Numbers are separated by tabs and line breaks. It is necessary to read the data from this file into a two-dimensional array.
Z.Y. As far as I know, it is possible to read data using:
fscanf(f,"%d", &temp);
But I would like to implement this using Qt.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
EXL, 2014-05-23
@EXL

#include <QVector>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QStringList>

#include <iostream>

const QString allFileToString(QFile &aFile)
{
    if (!aFile.open(QFile::ReadOnly | QFile::Text)) {
        std::cout << "Error opening file!" << std::endl;
        return NULL;
    }
    QTextStream in(&aFile);
    return in.readAll();
}

void setDataToVector(const QStringList &aStringList,
                     QVector< QVector <int> > &aVector)
{
    size_t x = aStringList.size() - 1; // Count of line, 8
    size_t y = aStringList.at(0).count("\t") + 1; // Count of digits in line, 6

    for (size_t i = 0; i < x; ++i) {
        QVector<int> temp_vector;
        for (size_t j = 0; j < y; ++j) {
            temp_vector.push_back(aStringList.at(i).split("\t").at(j).toInt());
        }
        aVector.push_back(temp_vector);
    }
}

void printVector(const QVector< QVector <int> > &aVector)
{
    for (int i = 0; i < aVector.size(); ++i) {
        for (int j = 0; j < aVector.at(0).size(); ++j) {
            std::cout << aVector.at(i).at(j) << "\t";
        }
        std::cout << std::endl;
    }
}

int main(/*int argc, char *argv[]*/)
{
    QVector< QVector <int> > vector;
    QFile file("test.txt");

    setDataToVector(allFileToString(file).split("\n"), vector);

    printVector(vector);

    return 0;
}

X
xandox, 2014-05-23
@xandox

QFile file("my_file");
file.open(QIODevice::ReadOnly);
QTextStream fileStream(&file);
QString str;
std::vector<std::vector<int>> array;
for (str = fileStrea.readLine(); !str.isNull(); str = fileStream.readLine()) {
    array.push_back(std::vector<int>);
    std::vector<int>& curr = array.back();
    QTextStream strStream(str);
    while(!strStream.atEnd()) {
         int number;
         stdStream >> number;
         curr.push_back(number);
    }
}

something like this. wrote here, it may not compile, but the idea should be clear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question