正在尝试从QT中的文件中读取行

Trying to read lines from file in QT

本文关键字:文件 读取 QT      更新时间:2023-10-16

我正在尝试从.txt文档中读取行,txt的格式是:

名称;姓氏;年龄住址车辙电话

名称;姓氏;年龄住址车辙电话

名称;姓氏;年龄住址车辙电话

当我点击名为"btnVerUsuarios"的按钮时,所有数据将同时显示在文本浏览器中,顺序如下:

名称:名称

姓氏:姓氏

年龄:年龄

地址:地址

RUT:RUT

电话:电话

还有两次使用所有数据

这就是我所拥有的,但当我试图执行这个程序时,出现了一个错误,我必须关闭程序:

void MainWindow::on_btnVerUsuarios_clicked()
{
    QFile F("datos.txt");
    F.open(QIODevice::ReadOnly);
    QTextStream leer(&F);            //here we have the content of the txt
    QStringList parsear;            //to parse the specific data from a line
    QString nombres;                  // to save the name
    QString apellidos;                // to save the lastname
    QString edad;                     // to save the age
    QString address;                  // to save the address
    QString rut;                      // to save the RUT
    QString fono;                     // to save the phone
    QString forma = "";               // to save all the data
    QString linea = leer.readLine();   // a line
    while (!linea.isNull()) {
        parsear = linea.split(";");      // parsing
        nombres = parsear[0];            // the names
        apellidos = parsear[1];          // the lastnames
        edad = parsear[2];               // the age
        address = parsear[3];            // the address
        rut = parsear[4];                // the RUT
        fono = parsear[5];               // the phone
        linea=leer.readLine();  //to select the next line (or that is what I want)
        forma = forma + "Nombres: "+nombres+"nApellidos: "+apellidos+"nEdad: "+edad+"nDirección: "+address+"nRUT: "+rut+"nTeléfono: "+fono+"nn";
    }   // The entire data with the required format is ok, now I have to put it in the textBrowser
    ui->textBrowser->setText(forma);  //putting the entire data int the textBrowser
}

如果还有其他简单的方法,请帮我。

抱歉我英语不好,谢谢。

编辑

我试图同时显示所有数据,如果我解释错了,很抱歉。不管怎样,多亏了Afflected的回答,我已经解决了我的问题。

读取整个文件并同时显示所有文件的最简单方法是类似

try 
{
  QFile ReadMyFile("File Path Here");
  if(!ReadMyFile.open(QIODevice::ReadOnly))
  QTextStream in(&ReadMyFile);
  QString GetContents = ReadMyFile.readAll();
  ui->textBrowser->setText(GetContents);
  ReadMyFile.close();
}
catch(...) // Generic catch used here, substitute with your own 
{ 
   // Print exception if one occurs
}

你应该总是安排一些异常处理,尤其是在处理文件时,如果定位文件等出现问题,你不希望你的程序立即崩溃

上面的代码只是将整个文件读取到一个字符串中,并将其全部打印到textBrowser中。有多种方法可以做到这一点,我不确定你的最终目标是什么,无论出于何种目的,这都比上面的要高效得多,但这不是你应该只复制粘贴并始终使用的东西。这是一个非常简单的例子,可以让你上路,它适用于大量文件。。。

据我所见,你想一次显示整个文件(这就是你上面所说的),但我不同意的是,你为什么要把每一件事都拆分并存储到各种QString中?

更新:

如果你不想改变你的写过程,把每个字段单独写出来并以换行符结尾(我建议你这样做),那么最好的方法是使用QLinkedList。如果你打算修改文件,你应该使用任何一种方法。。

http://doc-snapshots.qt.io/qt5-5.6/qlinkedlist.html

它是迭代器

http://doc-snapshots.qt.io/qt5-5.6/qlinkedlistiterator.html#QLinkedListIterator

这很简单,只需阅读文件,定位分隔符,并将下一个元素添加到链接列表中——我链接的文档将向您展示您可以使用它做的每一件事,希望这会有所帮助!