c++ - 由于 QTextStream 的无限循环
问题描述
所以,我在尝试从文件中读取行(逐行)时得到无限循环。我试图使用do{}while();
这样的循环:
QTextStream stream(stdin);
QString line;
do {
line = stream.readLine();
} while (!line.isNull());
但我得到空字符串。
当然,我检查了文件路径(它是正确的)。我试图使用/Users/user/tts.txt
路径但没有更改。我试图读取其他文件(如 m3u)。而且它不适用于 macOS Catalina、Windows 10、Linux (Debian)。
那么,为什么我会得到无限循环?
QStringList Manager::GetLinesFromFile(const QString &nameOfFile)
{
QStringList lines = {};
//path to file
const QString path = QCoreApplication::applicationDirPath() + "/bin/" + "tts.txt";
//"/Users/user/tts.txt"
QFile buffer;
buffer.QFile::setFileName(path);
#ifndef Q_DEBUG
qDebug() << path;
#endif
if(buffer.QFile::exists())
{
if(!buffer.QIODevice::open(QIODevice::ReadOnly))
{
#ifndef Q_DEBUG
qCritical() << "error: can't open file";
#endif
}
else
{
QTextStream stream(&buffer);
// both conditions
// (!stream.QTextStream::atEnd())
while(!buffer.QFileDevice::atEnd())
lines.QList::push_back(stream.QTextStream::readLine());
buffer.QFile::close();
}
}
else
{
#ifndef Q_DEBUG
qCritical() << "error: file not exists";
#endif
}
return lines;
}
解决方案
查看 QTextstream 文档https://doc.qt.io/qt-5/qtextstream.html。有一个逐行阅读的例子。您的 while 循环应该一直读取,直到流到达缓冲区的末尾,并且许多内置的读取函数将在他发生时返回 false
推荐阅读
- c++ - C++ 中“this”关键字的实现限制,因为它与危险但实用的示例有关
- css - 如何将 z-index 应用于伪元素
- tensorflow - 获取张量的动态形状
- ios - UICollectionView 不渲染单元格 - 没有代码只有故事板
- python - 对于在 Python 中使用 H2O 进行网格搜索,我们应该在哪里设置种子?
- kubernetes - Kubernetes 不接受新的作业定义
- javascript - 图例标签中的换行符
- c# - 使用方法字符串名称从其基抽象类调用派生类方法
- java - java.lang.AbstractMethodError:方法 DoublyLinkedList.isEmpty()Z 是抽象的吗?
- python - IBM Watson Speech to Text Audio/Basic 不接受窄带 .WAV