如何使用QFile,c ++从文件创建整数数组

时间:2017-06-09 21:27:43

标签: c++ qt qfile

我正在使用qtCreator

我有一个文件`file.txt`,如:

n a1 a2 a3.. an b1 b2 b3.. bn n1 n2 n3.. nn

n是矩阵的大小。

我需要从dat文件创建一个数组但是使用QFile,而不是ifstream。

2 个答案:

答案 0 :(得分:0)

这是将数据从txt文件存储到数字数组

的建议解决方案
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QVector>
#include <QStringList>

#include <iostream>

int main()
{
    QFile data("dat.txt");
    if (!data.open(QIODevice::ReadOnly | QIODevice::Text)){
        std::cout << "txt file can't be opened..." << std::endl;
        return -1;
    }

    QString matrixStrSize;
    QTextStream in(&data);
    in >> matrixStrSize;

    int matSize = matrixStrSize.toInt();

    QVector< QVector<int> > matrix;


    while (!in.atEnd()) {
        QString line = in.readLine();
        if(!line.isEmpty()){
            QStringList numsStr = line.split(" ");
            QVector<int> temp;
            for(int i(0); i < matSize; ++i){
                temp.push_back(numsStr[i].toInt());
            }
            matrix.push_back(temp);
        }
    }

    // Print data 
    std::cout << "mat[" << matSize << "][" << matSize << "] = " << std::endl;
    for(int i(0); i < matSize; ++i){
        for(int j(0); j < matSize; ++j)
            std::cout << matrix[i][j] << " ";
        std::cout << std::endl;
    }

    return 0;
}

我的案例中的文本文件是

5
1 2 3 4 5
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

前面代码的输出是

mat[5][5] =
1 2 3 4 5
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

答案 1 :(得分:0)

一种方法是编写一个解析矩阵的QTextStream::operator>>重载。

假设文件中只有一个矩阵,下面是一个完整的例子,意思是正确的,即我没有故意削减任何角落,代码应该在现实生活中正常工作情况 - 即它应该检测所有错误。我选择了一种矩阵格式,其中换行符不起任何作用 - 从它们是否应该的问题来看,它并不明显。

// https://github.com/KubaO/stackoverflown/tree/master/questions/file-matrix-read-44466934
#include <QtCore>
#include <cstdlib>

using Matrix = QVector<QVector<double>>;

// A valid matrix has a positive row size, and consists of a non-zero number of
// rows all having the same number of elements equal to the row size.
// Whitespace separates the elements.
// The matrix will be left unchanged if it doesn't conform to spec above, or if
// an I/O error had occurred. Non-conforming matrices set a ReadCorruptData
// status.
QTextStream & operator>>(QTextStream & in, Matrix & out) {
   Matrix matrix;
   int columns;
   in >> columns;
   if (in.status() != QTextStream::Ok)
      return in;
   if (columns <= 0) {
      in.setStatus(QTextStream::ReadCorruptData);
      return in;
   }
   for (int col = 0; !in.atEnd(); col++) {
      double element;
      in >> element;
      if (in.status() == QTextStream::ReadPastEnd)
         break;
      if (in.status() != QTextStream::Ok)
         return in;
      if (col >= columns)
         col = 0;
      if (col == 0) {
         matrix.push_back({});
         matrix.back().reserve(columns);
      }
      matrix.back().push_back(element);
   }
   if (!matrix.isEmpty() && matrix.back().size() == columns)
      out = matrix;
   else
      in.setStatus(QTextStream::ReadCorruptData);
   return in;
}

测试工具:

const char
rawData[] = "5\n"
            "1 2 3 4 5\n"
            "5 6 7 8 9\n"
            "10 11 12 13 14\n"
            "15 16 17 18 19\n"
            "20 21 22 23 24";

int main()
{
   auto data = QByteArray::fromRawData(rawData, sizeof(rawData)-1);
   QBuffer file(&data);
   if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
      return qCritical("Input file can't be opened."), EXIT_FAILURE;
   QTextStream in(&file);
   Matrix matrix;
   in >> matrix;
   qDebug() << matrix;
   Matrix compare{{1,2,3,4,5}, {5,6,7,8,9}, {10,11,12,13,14}, {15,16,17,18,19}, {20,21,22,23,24}};
   Q_ASSERT(matrix == compare);
}