Search code examples
c++qtqvectorqtextstream

Writing a QVector to a text file in Qt


I'm trying to write a program which reads in a text file containing several rows of 512 elements. These are numbers separated by a tab, the first line of the file contains general info about the file itself. Here's what it looks like:

512 Measurement taken on: Thu 12. Jun 18:35:44 2014 Comments: nil
2.4155 1.60983 1.08339 0 2.13321 0 0.848402 0 0.747692 0 0.146487 0 1.98062 0 0.846876 0 1.87991 0.117494 0 0 0 0 1.6907 0 0 0 0.0671397 0.256352 1.33974 1.4313 1.17494 0 0 0 1.83566 0 2.54826 0 0 0 0 0 1.80819 0 0 0 0 0 4.78523 0 1.99283 0 2.63676 0 2.19272 0 0.962844 0.256352 0.762951 0.581369 0 0 0 0.689708 1.38552 2.38193 1.11391 3.22118 0.712596 0 0.508125 0 0 0.842298 0 0.794995 0.967422 0.820935 0.0534066 2.67338 0

etc etc.

Each of the 512 columns represents a separate data stream and the rows are sampled over time. The program calculates the integral of the data so that it spits out a vector with 512 elements, each element is the sum of all the data in the respective column.

The integral part works fine, i can print the output of the vector using qDebug, but when I try and write the vector to a text file I get an error.

Here is the code I'm using:

void MainWindow::on_pushButton_clicked()

QVector<double> SingleLineData;
SingleLineData.resize(512);
QString test;
QString inputfile = QFileDialog::getOpenFileName(
            this,
            tr("Open File"),
            "/Users",
            "All files (*.*)"
            );

if(inputfile != ""){
QFile file(inputfile);


if(!file.open(QFile::ReadOnly)){
   }
QTextStream in(&file);


    double buffer;

    while(!file.atEnd()){
        in.readLine();
        for(int i=0; i<512; i++){
            in >> buffer;
            SingleLineData[i]+=buffer;
        }
    }

}
    qDebug() << SingleLineData;

// ************* file output **************************************************

QString filename = "/Users/Mitch/Desktop/integral.txt";
QFile fileout(filename);
if (fileout.open(QFile::ReadWrite | QFile::Text)){
}
     QTextStream out(&fileout);
     out << SingleLineData;
     fileout.close();

}

And the error is receive says:

error: invalid operands to binary expression ('QTextStream' and 'QVector') and candidate function not viable: no known conversion from 'QVector' to 'const void *' for 1st argument; take the address of the argument with & QTextStream &operator<<(const void *ptr);

Any help would be much appreciated! :)


Solution

  • This is the iterator method. The operator for QTextStream is not overloaded to accept a vector. However, it can accept a double.

    QString filename = "/Users/Mitch/Desktop/integral.txt";
    QFile fileout(filename);
    if (fileout.open(QFile::ReadWrite | QFile::Text)){
     QTextStream out(&fileout);
     for (Qvector<double>::iterator iter = SingleLineData.begin(); iter != SingleLineData.end(); iter++){
         out << *iter;
     }
     fileout.close();
    }