QTextStream Class

The QTextStream class provides a convenient interface for reading and writing text. More...

Header: #include <QTextStream>
qmake: QT += core

Note: All functions in this class are reentrant.

Public Types

enum FieldAlignment { AlignLeft, AlignRight, AlignCenter, AlignAccountingStyle }
enum NumberFlag { ShowBase, ForcePoint, ForceSign, UppercaseBase, UppercaseDigits }
enum RealNumberNotation { ScientificNotation, FixedNotation, SmartNotation }
enum Status { Ok, ReadPastEnd, ReadCorruptData, WriteFailed }

Detailed Description

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. For generating text, QTextStream supports formatting options for field padding and alignment, and formatting of numbers. Example:

 QFile data("output.txt");
 if (data.open(QFile::WriteOnly | QFile::Truncate)) {
     QTextStream out(&data);
     out << "Result: " << qSetFieldWidth(10) << left << 3.14 << 2.7;
     // writes "Result: 3.14      2.7       "
 }

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;
 while (stream.readLineInto(&line)) {
     ...
 }

Besides using QTextStream's constructors, you can also set the device or string QTextStream operates on by calling setDevice() or setString(). You can seek to a position by calling seek(), and atEnd() will return true when there is no data left to be read. If you call flush(), QTextStream will empty all data from its write buffer into the device and call flush() on the device.

Internally, QTextStream uses a Unicode based buffer, and QTextCodec is used by QTextStream to automatically support different character sets. By default, QTextCodec::codecForLocale() is used for reading and writing, but you can also set the codec by calling setCodec(). Automatic Unicode detection is also supported. When this feature is enabled (the default behavior), QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and switch to the appropriate UTF codec when reading. QTextStream does not write a BOM by default, but you can enable this by calling setGenerateByteOrderMark(true). When QTextStream operates on a QString directly, the codec is disabled.

There are three general ways to use QTextStream when reading text files:

  • Chunk by chunk, by calling readLine() or readAll().
  • Word by word. QTextStream supports streaming into QStrings, QByteArrays and char* buffers. Words are delimited by space, and leading white space is automatically skipped.
  • Character by character, by streaming into QChar or char types. This method is often used for convenient input handling when parsing files, independent of character encoding and end-of-line semantics. To skip white space, call skipWhiteSpace().

Since the text stream uses a buffer, you should not read from the stream using the implementation of a superclass. For instance, if you have a QFile and read from it directly using QFile::readLine() instead of using the stream, the text stream's internal position will be out of sync with the file's position.

By default, when reading numbers from a stream of text, QTextStream will automatically detect the number's base representation. For example, if the number starts with "0x", it is assumed to be in hexadecimal form. If it starts with the digits 1-9, it is assumed to be in decimal form, and so on. You can set the integer base, thereby disabling the automatic detection, by calling setIntegerBase(). Example:

 QTextStream in("0x50 0x20");
 int firstNumber, secondNumber;

 in >> firstNumber;             // firstNumber == 80
 in >> dec >> secondNumber;     // secondNumber == 0

 char ch;
 in >> ch;                      // ch == 'x'

QTextStream supports many formatting options for generating text. You can set the field width and pad character by calling setFieldWidth() and setPadChar(). Use setFieldAlignment() to set the alignment within each field. For real numbers, call setRealNumberNotation() and setRealNumberPrecision() to set the notation (SmartNotation, ScientificNotation, FixedNotation) and precision in digits of the generated number. Some extra number formatting options are also available through setNumberFlags().

Like <iostream> in the standard C++ library, QTextStream also defines several global manipulator functions:

ManipulatorDescription
Qt::binSame as setIntegerBase(2).
Qt::octSame as setIntegerBase(8).
Qt::decSame as setIntegerBase(10).
Qt::hexSame as setIntegerBase(16).
Qt::showbaseSame as setNumberFlags(numberFlags() | ShowBase).
Qt::forcesignSame as setNumberFlags(numberFlags() | ForceSign).
Qt::forcepointSame as setNumberFlags(numberFlags() | ForcePoint).
Qt::noshowbaseSame as setNumberFlags(numberFlags() & ~ShowBase).
Qt::noforcesignSame as setNumberFlags(numberFlags() & ~ForceSign).
Qt::noforcepointSame as setNumberFlags(numberFlags() & ~ForcePoint).
Qt::uppercasebaseSame as setNumberFlags(numberFlags() | UppercaseBase).
Qt::uppercasedigitsSame as setNumberFlags(numberFlags() | UppercaseDigits).
Qt::lowercasebaseSame as setNumberFlags(numberFlags() & ~UppercaseBase).
Qt::lowercasedigitsSame as setNumberFlags(numberFlags() & ~UppercaseDigits).
Qt::fixedSame as setRealNumberNotation(FixedNotation).
Qt::scientificSame as setRealNumberNotation(ScientificNotation).
Qt::leftSame as setFieldAlignment(AlignLeft).
Qt::rightSame as setFieldAlignment(AlignRight).
Qt::centerSame as setFieldAlignment(AlignCenter).
Qt::endlSame as operator<<('\n') and flush().
Qt::flushSame as flush().
Qt::resetSame as reset().
Qt::wsSame as skipWhiteSpace().
Qt::bomSame as setGenerateByteOrderMark(true).

In addition, Qt provides three global manipulators that take a parameter: qSetFieldWidth(), qSetPadChar(), and qSetRealNumberPrecision().

See also QDataStream, QIODevice, QFile, QBuffer, QTcpSocket, and Text Codecs Example.

Member Type Documentation

enum QTextStream::FieldAlignment

This enum specifies how to align text in fields when the field is wider than the text that occupies it.

ConstantValueDescription
QTextStream::AlignLeft0Pad on the right side of fields.
QTextStream::AlignRight1Pad on the left side of fields.
QTextStream::AlignCenter2Pad on both sides of field.
QTextStream::AlignAccountingStyle3Same as AlignRight, except that the sign of a number is flush left.

See also setFieldAlignment().

enum QTextStream::NumberFlag

This enum specifies various flags that can be set to affect the output of integers, floats, and doubles.

ConstantValueDescription
QTextStream::ShowBase0x1Show the base as a prefix if the base is 16 ("0x"), 8 ("0"), or 2 ("0b").
QTextStream::ForcePoint0x2Always put the decimal separator in numbers, even if there are no decimals.
QTextStream::ForceSign0x4Always put the sign in numbers, even for positive numbers.
QTextStream::UppercaseBase0x8Use uppercase versions of base prefixes ("0X", "0B").
QTextStream::UppercaseDigits0x10Use uppercase letters for expressing digits 10 to 35 instead of lowercase.

See also setNumberFlags().

enum QTextStream::RealNumberNotation

This enum specifies which notations to use for expressing float and double as strings.

ConstantValueDescription
QTextStream::ScientificNotation2Scientific notation (printf()'s %e flag).
QTextStream::FixedNotation1Fixed-point notation (printf()'s %f flag).
QTextStream::SmartNotation0Scientific or fixed-point notation, depending on which makes most sense (printf()'s %g flag).

See also setRealNumberNotation().

enum QTextStream::Status

This enum describes the current status of the text stream.

ConstantValueDescription
QTextStream::Ok0The text stream is operating normally.
QTextStream::ReadPastEnd1The text stream has read past the end of the data in the underlying device.
QTextStream::ReadCorruptData2The text stream has read corrupt data.
QTextStream::WriteFailed3The text stream cannot write to the underlying device.

See also status().