正在尝试从QT中的文件中读取行
Trying to read lines from file in QT
我正在尝试从.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
这很简单,只需阅读文件,定位分隔符,并将下一个元素添加到链接列表中——我链接的文档将向您展示您可以使用它做的每一件事,希望这会有所帮助!
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量