PDA

View Full Version : QTextStream with stdout



fyodor
3rd December 2011, 22:05
Hello. I am trying to do simple hello world console app with Qt. I use Qt 4.7.4 libraries and QtCreator 2.3.1 on Windows 7 x64 Home Premium SP1. When I build and run it nothing happens. Just a blank console appears. Here is code:

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str = "Hello World";
QTextStream out(stdout, QIODevice::WriteOnly);

out << str;

return a.exec();
} and .pro file:

#-------------------------------------------------
#
# Project created by QtCreator 2011-12-03T21:44:19
#
#-------------------------------------------------

QT += core

QT -= gui

TARGET = untitled
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app


SOURCES += main.cpp I tried on OSX Lion 10.7.2 but the result is same. So is it a bug or am I doing something wrong?

Zlatomir
3rd December 2011, 22:39
That happens because you start an event-loop that just loops without doing nothing - i'm talking about the creation of that QCoreApplication and the call of exec().

For your "hello world" app you can skip the QCoreApplication and it's exec, so your main will look something like:


int main(int argc, char *argv[])
{
QString str = "Hello World\n";
QTextStream out(stdout, QIODevice::WriteOnly);

out << str;
//out.flush(); //a stream flush might be necessary to see the results immediately
return 0;
}

fyodor
3rd December 2011, 23:10
Thanks. It works. But Then why do we need QCoreApplication in console app if it can break something?

Zlatomir
4th December 2011, 00:05
You might need QCoreApplication if, for example, you code a "server"-side application that doesn't have a GUI but it waits for events (eg: some network requests from the "client"-side applications) - this is just the first example that crossed my mind, i'm sure there are other usages.