【问题标题】:Qt - QTextStream - How to set cursor position to beginning of a line?Qt - QTextStream - 如何将光标位置设置为行首?
【发布时间】:2013-05-21 11:34:18
【问题描述】:

readLine()之后,如何设置光标位置到行首?

使用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();
    }

【问题讨论】:

  • 你真正需要做什么?
  • 我用 readLine() 读取了一行,我希望流中的光标回到行的开头
  • 您希望得到什么?描述你想要得到的结果。
  • 我想从文件中读取对象,并根据每行的第一个单词使用不同的对象构造函数

标签: c++ qt cursor readline qtextstream


【解决方案1】:

所以,您需要(反)序列化

尝试做正确的事。 这是官方文档:http://qt-project.org/doc/qt-4.8/datastreamformat.html 这是示例:Serialization with Qt

【讨论】:

    【解决方案2】:

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

    这里是 ma​​in.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      相关资源
      最近更新 更多