2013-05-26 152 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