QT中读取文本数据(txt)

      下面的代码实现读取txt文档中的数据,并且是一行一行的读取。

void MainWindow::on_pushButton_clicked()
{
  QFile file("abcd.txt");
  if(! file.open(QIODevice::ReadOnly|QIODevice::Text))
      qDebug()<<file.errorString();
  else
       qDebug()<<"openok";
  file.seek(0);

  QTextStream shuru(&file);
  while(! shuru.atEnd())
  {
      QString line=shuru.readLine();
      qDebug()<<line;
  }
  file.close();
}

 

上面输出的是字符串格式,可能有时候要用到的是int float这样的格式,程序修改如下:

void MainWindow::on_pushButton_clicked()
{
  int aa;
  int bb;
  int cc;
  char ch;
  float dd;

  QFile file("abcd.txt");
  if(! file.open(QIODevice::ReadOnly|QIODevice::Text))
      qDebug()<<file.errorString();
  else
       qDebug()<<"openok";
  file.seek(0);

  QTextStream shuru(&file);
  while(! shuru.atEnd())
  {
    QString line=shuru.readLine();
    QStringList strlist=line.split(",");
    //for(int i=0;i<strlist.size();i++)
    //{
        //qDebug()<<strlist[i];
        aa=strlist[0].toInt();
        bb=strlist[1].toInt();
        cc=strlist[2].toInt();
        //ch=strlist[3];
        dd=strlist[4].toFloat();
    //}
    qDebug()<<aa;
    qDebug()<<bb;
    qDebug()<<cc;
    //qDebug()<<ch;
    qDebug()<<dd;
  }
  file.close();
}

 

posted @ 2014-10-13 13:51  一般首席  阅读(7694)  评论(0编辑  收藏  举报