[英]how to read only one line in a text file which has particular word using Qt
I am reading a .txt file, I want to read only 1 line with particular word. 我正在读取.txt文件,我只想读取包含特定单词的1行。 I'm using Qt Creator .
我正在使用Qt Creator 。
How can I achieve this? 我该如何实现?
This is my code so far: 到目前为止,这是我的代码:
QFile file("/home/a1.txt");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this,"title","file not open");
}
QTextStream in(&file);
QString text = in.readAll();
ui->plainTextEdit->setPlainText(text);
file.close();
If you want to search all lines for a specific word you can do this 如果要在所有行中搜索特定单词,可以执行此操作
QFile file("/home/a1.txt");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this,"title","file not open");
}
QTextStream in(&file);
QString text;
while (!in.atEnd()) {
text = in.readLine();
if (text.contains(/*Search her for the word you want.*/))
break;
}
ui->plainTextEdit->setPlainText(text);
file.close();
So you loop through all lines. 因此,您可以遍历所有行。 And in every line you check if the word exist.
然后在每一行中检查单词是否存在。 If yes you can stop searching and leave the loop.
如果是,则可以停止搜索并退出循环。
I hope this helps! 我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.