krish
krish

Reputation: 41

read the data from text file in QT

I have to read the data from text file in QT which has data in this form

1 1
2 4
3 9
4 16
5 25

I would like to take every integer or float number and assign it to a array variable like

X[0]=1, Y[0]=1 & 
X[1]=2, Y[1]=4  and so on....  

enter code here
QString filename=QFileDialog::getOpenFileName(this, tr("Open File"), "media://", "All files (*.*);; Text File (*.txt)");

QFile file3(filename);

if(!file3.open(QFile::ReadOnly|QFile::Text))
QMessageBox::information(0,"info", file3.errorString());


QTextStream in3(&file3);

QString xv,*p,xx,yy;

QStringList L;

for(j=0;j<n;j++)
{
 xv = in3.readLine();
 p[0]=xv;
 p[1]=xv;
 xx=p[0];
 yy=p[1];

 L=xx.split(" ");

 L=yy.split(" ");

 X[j]=L[0].toFloat();

 ui->xvalue->addItem(QString::number((X[j])));

 xv.split(" ", QString::SkipEmptyParts);

 Y[j]=L[1].toFloat();

 ui->yvalue->addItem(QString::number((Y[j])));

 }`

I tried many ways but nothing worked for me

Upvotes: 0

Views: 5079

Answers (2)

Edwin Rodr&#237;guez
Edwin Rodr&#237;guez

Reputation: 1257

The easiest way is to use QTextStream

#include <QFile>
#include <QTextStream>

QFile f("your.file");
f.open(QIODevice::ReadOnly);
QTextStream s(&f);

while ( !s.atEnd() ) {
  double d;
  s >> d;
  // append d to some list;
}

Upvotes: 2

Michael B.
Michael B.

Reputation: 145

if(!file3.open(QFile::ReadOnly|QFile::Text)){
    QMessageBox::information(0,"info", file3.errorString());

That's bad, you need to handle the error wit more than a messagebox, or enclose to the rest in an else statement.

*p

Why is one of those strings a pointer?

for(j=0;j<n;j++)  

you haven't declared n.. does this even compile?

X[j]=L[0].toFloat();

Why are you incrementing your array by the j iterator? You are going to get a memory error immediately because you will never have more than [1] since you only have a single split per line with 2 floats per line. You really only need to access [0] and [1]

Just in general you need to use containers and memory safe code, not raw arrays. Plus I may be lost in your fun variable naming but why convert it to a float, then convert it right back into a QString? Just plug it straight into your ui element.

while (!file.atEnd()) {
    QString line = in.readLine();
    QStringList list = line.split(" ");
       ui->xvalue->addItem(line[0]);
       ui->xvalue->addItem(line[1]);
    }
}

Upvotes: 0

Related Questions