c++ - 如何读取特定单词之间的文本文件?

标签 c++ qt

我想要“配置文件名称”和“###”之间的文本。提取的文本应显示在文本浏览器中。配置文件名称不同。我的文本文件 (harnish_data.txt) 看起来像这样,

XYZ Profile
First Name :- XYZ
Second Name :- sssss
Last Name :- sssss

Favourite Food :- sssss
Favourite Actor :- sssss
Favourite Actress :- ssssss
###
PQR Profile
First Name :- PQR
Second Name :- hhhhh
Last Name :- hhhhh

Favourite Food :- hhhhhh
Favourite Actor :- hhhhhh
Favourite Actress :- hhhhh
###

现在,如果配置文件名称是 XYZ,那么我想要 XYZ 配置文件与 ### 之间的文本数据。如果配置文件名称是 PQR,那么我希望 PQR 配置文件与 ### 之间的文本。配置文件的编号可能会增加。

我试过这样,这里的 detail_data.txt 文件只包含我的个人资料名称。

QFile file("detail_data.txt");
file.open(QIODevice::ReadWrite);
QTextStream inn(&file);
const QString contentt = inn.readLine(); //contentt contain profile name
qDebug() << contentt; // PQR

QFile MyFile("harnish_data.txt"); // contains profile data
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);
const QString content = in.readAll();  // contains profile data

QString srch (contentt + " " + "Profile");
qDebug() << srch << "search string"; // PQR Profile
int pos = content.indexOf(srch);
qDebug() << pos << "index of srch"; //155

if ( pos >= 0 )
{
    QString restOfLine = content.mid(pos + srch.length(), srch.endsWith("###"));
    qDebug() << srch.length() << "srch.length()"; //11
    qDebug() << restOfLine << "restOfLine of mid"; //\nFirst Name :- PQR\nSecond Name :- hhhhh\nLast Name :- hhhhh\n\nFavourite Food :- hhhhhh\nFavourite Actor :- hhhhhh\nFavourite Actress :- hhhhh\n###\n\n" restOfLine of mid
}
ui->textBrowser->setText(in.readAll());

我已经运行了上面的代码,但它给了我完整的文本文件数据,而我想要的是“配置文件名称”和“###”之间的数据。

最佳答案

你的错误在这一行:

ui->textBrowser->setText(in.readAll());

应该是:

ui->textBrowser->setText(restOfLine);

首先搜索配置文件索引,然后搜索三个#:

QString srch(contentt + " " + "Profile");
int pos = content.indexOf(srch);
QString srch2("###");
int pos2 = content.indexOf(srch2);
if ( pos1 >= 0 && pos2 >= 0)
    QString restOfLine = content.mid(pos1, pos2-pos1);

关于c++ - 如何读取特定单词之间的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903923/

相关文章:

c++ - 使循环边界无效

c++ - 制作并重新编译带有子目录的 header

c++ - QML 访问不可调用函数

qt - 是否可以在 Qt Creator 中将 Qt 样式表与提升的小部件一起使用?

linux - 不通过 QSqlQuery 获取所有 sqlite 编译指示的结果

Java 等效于 C++ Botan 函数调用

c++ - 使用 fstream tellg 读取流的一部分直到结束

c++ - C++内存管理相关查询

c++ - QGraphicsItem 和 Tab 键顺序

linux - 未加载 QIBASE 驱动程序