Qt5 Tutorial QTextStream - 2020
bogotobogo.com site search:
QStringList
In this tutorial, we will learn about QTextStream.
The QTextStream class provides a convenient interface for reading and writing text.
QTextStream can operate on a QIODevice, a QByteArray or a QString. Using QTextStream's streaming operators, you can conveniently read and write words, lines and numbers.
Simple example will be enough to figure out how the QTextStream works.
#include <QCoreApplication> #include <QTextStream7gt; #include <QFile> #include <QDebug7gt; void write() { QFile file("C:/Test/simple.txt"); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { // We're going to streaming text to the file QTextStream stream(&file;); stream << "Debussy\n"; stream << "Rabel\n"; file.close(); qDebug() << "Writing finished"; } } void read() { QFile file("C:/Test/simple.txt"); if(file.open(QIODevice::ReadOnly|QIODevice::Text)) { // We're going to streaming the file // to the QString QTextStream stream(&file;); QString line; do { line = stream.readLine(); qDebug() << line; } while(!line.isNull()); file.close(); qDebug() << "Reading finished"; } } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); write(); read(); return a.exec(); }
Output:
Writing finished "Debussy" "Rabel" "" Reading finished
It's also common to use QTextStream to read console input and write console output. QTextStream is locale aware, and will automatically decode standard input using the correct codec. Example:
QTextStream stream(stdin); QString line; do { line = stream.readLine(); } while (!line.isNull());
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization