3.2.1.  Streams and Dates

[ fromfile: qtcore.xml id: qstreams ]

In subsequent examples, we use instances of QTextStream, which behave in a similar way to the C++ Standard Library's global iostream objects. We have given them the familiar names: cin, cout, and cerr. For convenience, we have placed these definitions, along with some other useful functions, into a namespace so that they can be easily added to any program.

Example 3.1. src/libs/utils/qstd.h

[ . . . . ]
namespace qstd {
     UTILS_EXPORT bool yes(QString yesNoQuestion);
     UTILS_EXPORT  bool more(QString prompt);
     UTILS_EXPORT int promptInt(int base = 10);
     UTILS_EXPORT double promptDouble();
     UTILS_EXPORT void promptOutputFile(QFile& outfile);
     UTILS_EXPORT void promptInputFile(QFile& infile);
[ . . . . ]

Example 3.1 declares the iostream-like QTextStreams, and Example 3.2 contains the required definitions of these static objects.

Example 3.2. src/libs/utils/qstd.cpp

[ . . . . ]

static QTextStream cout(stdout, QIODevice::WriteOnly);
static QTextStream cin(stdin, QIODevice::ReadOnly);
static QTextStream cerr(stderr, QIODevice::WriteOnly);

<QTextStream> works with Unicode QStrings and other Qt types, so we will use it in favor of <iostream> in most of our examples henceforth. Example 3.3 uses QTextStream objects and functions from the qstd namespace described. It also uses some of the QDate member functions and displays dates in several different formats.

Example 3.3. src/qtio/qtio-demo.cpp

[ . . . . ]
int main() {
    QTextStream cout(stdout);
    using namespace qstd;
    QDate d1(2002, 4,1), d2(QDate::currentDate());
    int days;
    cout << "The first date is: " << d1.toString()
            << "\nToday's date is: " 
            << d2.toString("ddd MMMM d, yyyy")<< endl;

    if (d1 <  d2)
        cout << d1.toString("MM/dd/yy") << " is earlier than " 
                << d2.toString("yyyyMMdd") << endl;

    cout << "There are " << d1.daysTo(d2) 
            << " days between "
            << d1.toString("MMM dd, yyyy") << " and " 
            << d2.toString(Qt::ISODate)  << endl;

    cout << "Enter number of days to add to the first date: " 
            <<  flush;
    days = promptInt();
    cout << "The first date was " << d1.toString()
            << "\nThe computed date is " 
            <<  d1.addDays(days).toString() << endl;
    cout << "First date displayed in longer format: "
            << d1.toString("dddd, MMMM dd, yyyy")  << endl;
[ . . . . ]

Here is the output of this program.

The first date is: Mon Apr 1 2002
Today's date is: Wed January 4, 2006
04/01/02 is earlier than 20060104
There are 1374 days between Apr 01, 2002 and 2006-01-04
Enter number of days to add to the first date: : 1234
The first date was Mon Apr 1 2002
The computed date is Wed Aug 17 2005
First date displayed in longer format: Monday, April 01, 2002