2013-05-26 108 views
0

readLine()之后,如何将光标位置设置为一行的起始位置?Qt - QTextStream - 如何将光标位置设置为行首?

使用seek()pos()不适合我。

这里是我的file.txt的什么样子:

Object1 Some-name 2 3.40 1.50 

Object2 Some-name 2 3.40 1.50 3.25 

Object3 Some-name 2 3.40 1.50 

这里是我的代码:

QFile file("file.txt"); 
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { 
     QTextStream stream(&file); 

     while(!stream.atEnd()) { 
      qint64 posBefore = file.pos(); 
      QString line = stream.readLine(); 
      QStringList splitline = line.split(" "); 

      if(splitline.at(0) == "Object1") { 
       stream.seek(posBefore); 
       object1 tmp; 
       stream >> tmp; 
       tab.push_back(tmp); 
      } 

      if(splitline.at(0) == "Object2") { 
       stream.seek(posBefore); 
       object2 tmp; 
       stream >> tmp; 
       tab.push_back(tmp); 
      } 

      if(splitline.at(0) == "Object3") { 
       stream.seek(posBefore); 
       object3 tmp; 
       stream >> tmp; 
       tab.push_back(tmp); 
      } 

     } 
     file.close(); 
    } 
+0

什么你真的需要做什么? – troyane

+0

我用readLine()读了一行,并且希望流中的光标返回到行的开始位置 – user2224198

+0

您期望得到什么?描述你想得到的结果。 – troyane

回答

0

我做了一个简单的控制台应用程序为您服务。你需要做的只是一个很好的旧QString::split()空格,并采取行中的第一个元素,但你喜欢,我通过QString::section()方法。

那么这里是的main.cpp代码:

#include <QtCore/QCoreApplication> 
#include <QFile> 
#include <QStringList> 
#include <QDebug> 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 

    QFile f("file.txt"); 
    f.open(QIODevice::ReadOnly); 
    // next line reads all file, splits it by newline character and iterates through it 
    foreach (QString i,QString(f.readAll()).split(QRegExp("[\r\n]"),QString::SkipEmptyParts)){ 
    QString name=i.section(" ",0,0); 
    // we take first section of string from the file, all strings are stored in "i" variable 
    qDebug()<<"read new object - "<<name; 
    } 
    f.close(); 
    return a.exec(); 
} 

file.txt文件是在同一目录下的可执行文件,并为您的文件副本:

Object1 Some-name 2 3.40 1.50 

Object2 Some-name 2 3.40 1.50 3.25 

Object3 Some-name 2 3.40 1.50