Solved

Running a C++ console in Qt

Posted on 2013-01-28
23
1,027 Views
Last Modified: 2013-01-28
Hi I am new to Qt and am trying to get a simple program to run in a console window just to test out QTextStream. The program compiles and runs with no errors but the console window is blank and when I enter some text and press enter it flashes up with the text that is meant to be displayed and closes. No idea why this is happening. My code is
#include <QTextStream>

using namespace std;

QTextStream cout(stdout);
QTextStream cin(stdin);

int main() {
    cout << "Hello World";
    int num;
    cout << "Enter a number";
    cin >> num;
    cout << "your number was" << num << endl;
    return 0;
        }

Open in new window

I also tried this with the same result.
#include <QtCore/QCoreApplication>
#include <QTextStream>
using namespace std;

QTextStream cout(stdout);
QTextstream cin(stdin);

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout << "Hello World" << endl;
    cout << "Enter a number";
    int num;
    cin >> num;
    cout << "Your number is " << num;
    return a.exec();
    
}

Open in new window

0
Comment
Question by:Dmon443
  • 10
  • 9
  • 2
  • +1
23 Comments
 
LVL 37

Expert Comment

by:TommySzalapski
ID: 38826851
Qt's text streams might not flush automatically. Try adding the line cout.flush(); when you want it to actually output the data.
Something like:
int main() {
    int num;
    cout << "Hello World";
    cout << "Enter a number";
    cout.flush():
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    return 0;
        }

Open in new window


Note: Since it does appear to flush when the object is destroyed, that second flush line isn't needed but it would be a good habit.
0
 

Author Comment

by:Dmon443
ID: 38826911
ok tried adding those lines but still same problem, runs a blank console window until something is entered and enter is pressed then closes the window with a flash of the hello world text.
0
 

Author Comment

by:Dmon443
ID: 38826936
So I closed Qt creator and opened again with run as administrator with this as my code
#include <QTextStream>

using namespace std;

QTextStream cout(stdout);
QTextStream cin(stdin);

int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    return 0;
}

Open in new window


now it pauses before I enter the number but as soon as I hit enter after putting a number in it closes straight away, how do I get to pause it after everything has ran?
0
 
LVL 22

Expert Comment

by:ambience
ID: 38827284
This should do

int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    cin.get();
    return 0;
}
0
 
LVL 86

Expert Comment

by:jkr
ID: 38827289
Why not using the standard (i.e. predefined) C++ streams, e.g.

#include <iostream>

using namespace std;

int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    return 0;
}
                                            

Open in new window


?
0
 
LVL 22

Expert Comment

by:ambience
ID: 38827310
sorry, has to be

cin.readLine();

didnt realize it a QTextStream
0
 
LVL 37

Expert Comment

by:TommySzalapski
ID: 38827535
Why do you want it to pause? Don't run it by double clicking on the executable. Pull up a command prompt and type the executable name there. That way you don't need to add unused input commands.
0
 

Author Comment

by:Dmon443
ID: 38827722
I'm running it within Qt creator and I want it to stay there so I can see if the program ran correctly. Also adding the cin.readLine(); doesn't change anything
0
 
LVL 86

Expert Comment

by:jkr
ID: 38827773
What about

QTest::qSleep(10000);

Open in new window


then (th eargument is ms, see http://qt-project.org/doc/qt-4.8/qtest.html) - BTW, 'QTest::qWait()' would also work.
0
 

Author Comment

by:Dmon443
ID: 38827984
ok so this is my new code now
#include <QTextStream>
#include <QtTest/qtest.h>
using namespace std;

QTextStream cout(stdout);
QTextStream cin(stdin);

int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    QTest::qWait(10000);
    return 0;
}

Open in new window

it now gives a build error :: error: collect2: ld returned 1 exit status
0
 
LVL 86

Expert Comment

by:jkr
ID: 38828008
>>it now gives a build error :: error: collect2: ld returned 1 exit status

Could you post the full build output (check the tabs on the lower right)?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:Dmon443
ID: 38828194
Running build steps for project first...
Configuration unchanged, skipping qmake step.
Starting: "C:/Qt/2010.04/mingw/bin/mingw32-make.exe" -w
mingw32-make: Entering directory `C:/Unisa/COS2614/first-build-desktop'
C:/Qt/2010.04/mingw/bin/mingw32-make -f Makefile.Debug
mingw32-make[1]: Entering directory `C:/Unisa/COS2614/first-build-desktop'
g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_CORE_LIB -DQT_THREAD_SUPPORT -I"..\..\..\Qt\2010.04\qt\include\QtCore" -I"..\..\..\Qt\2010.04\qt\include" -I"..\..\..\Qt\2010.04\qt\include\ActiveQt" -I"debug" -I"..\first" -I"." -I"..\..\..\Qt\2010.04\qt\mkspecs\win32-g++" -o debug\main.o ..\first\main.cpp
g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -Wl,-subsystem,console -mthreads -Wl -o debug\first.exe debug/main.o -L"c:\Qt\2010.04\qt\lib" -lQtCored4
mingw32-make[1]: Leaving directory `C:/Unisa/COS2614/first-build-desktop'
debug/main.o:C:\Unisa\COS2614\first-build-desktop/../../../Qt/2010.04/qt/include/QtTest/../../src/testlib/qtestsystem.h:70: undefined reference to `QTest::qSleep(int)'
collect2: ld returned 1 exit status
mingw32-make[1]: *** [debug\first.exe] Error 1
mingw32-make: Leaving directory `C:/Unisa/COS2614/first-build-desktop'
mingw32-make: *** [debug] Error 2
The process "C:/Qt/2010.04/mingw/bin/mingw32-make.exe" exited with code %2.
Error while building project first (target: Desktop)
When executing build step 'Make'
0
 
LVL 86

Expert Comment

by:jkr
ID: 38828238
Ah, you have to add 'testlib' to your .pro file, e.g.

 QT += testlib

Open in new window

0
 

Author Comment

by:Dmon443
ID: 38828285
ok now there is a new problem alltogether, when I run it the console crashes at the end. "first.exe has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available" close program.
0
 
LVL 86

Expert Comment

by:jkr
ID: 38828319
On which line does that occur when you run the executable under the Qt Debugger ? To do that, select "Debug|Start Debugging..." in QtCreator's main menu,
0
 

Author Comment

by:Dmon443
ID: 38828391
When I start the debug it runs in the debug window but never finishes, my mouse cursor has a "thinking" circle constantly going when I mouseover the debug pane. I clicked pause on the debugger and got this, screenshot attacheddebug
0
 
LVL 86

Expert Comment

by:jkr
ID: 38828440
Hm, that's odd. OK, let's try to narrow that down a little, do you get the same issue at the end of your program if you use

#include <iostream>

//#include <QTextStream>
//#include <QtTest/qtest.h>
using namespace std;

//QTextStream cout(stdout);
//QTextStream cin(stdin);
int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    QTest::qWait(10000);
    return 0;
}
                                            
                                            

Open in new window


instead?
0
 

Author Comment

by:Dmon443
ID: 38828463
Tried that, had to also // out the QTest line. Now I get :: error: cannot open output file debug\first.exe: Permission denied
:: error: collect2: ld returned 1 exit status
0
 
LVL 86

Expert Comment

by:jkr
ID: 38828497
Try to terminate all running instances of 'first.exe' with the Task Manager, seems that one is still running ;o)
0
 

Author Comment

by:Dmon443
ID: 38828523
Yes you are right! So now if I run it with iostream it runs fine but closes the console window as soon as I enter the number, if I use QTextStream then it crashes after I enter the number, if I // out the QTest line then it stops it from crashing but it closes straight after I enter the number like with iostream. the only thing I can think of is that I put the QT       += testlib in the wrong place. Here is the .pro file
#-------------------------------------------------
#
# Project created by QtCreator 2013-01-28T15:59:50
#
#-------------------------------------------------

QT       += core

QT       -= gui
QT       += testlib
TARGET = first
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp

Open in new window

0
 
LVL 86

Expert Comment

by:jkr
ID: 38828562
No, that shouldn't matter here. Since I noticed you are on Windows, you could replace the QTest stuff with a 'Sleep()' (requires adding '#include <windows.h>', 'qSleep()' will end up calling that one anyway), e.g.

#include <QTextStream>
using namespace std;

QTextStream cout(stdout);
QTextStream cin(stdin);

int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    Sleep(10000);
    return 0;
}
                                            

Open in new window

0
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 38828574
Ooops, that should have been

#include <windows.h>
#include <QTextStream>
using namespace std;

QTextStream cout(stdout);
QTextStream cin(stdin);

int main() {
    int num;
    cout << "Hello World" << endl;
    cout << "Enter a number ";
    cout.flush();
    cin >> num;
    cout << "your number was" << num << endl;
    cout.flush();
    Sleep(10000);
    return 0;
}
                                            
                                            

Open in new window

0
 

Author Comment

by:Dmon443
ID: 38828647
Great that works, thanks. Seems Qt creator is the problem here as it doesn't keep the console window open by default. Don't know why you would make a program that makes it so difficult to see how the program runs in a console, I guess Qt is supposed to be used primarily for GUI programming so maybe that's why. Anyways thanks for the help.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
firstChar challenge 13 85
Exception thrown at 0x00007FFD5BC81F28 7 31
C Programming - If Statement 8 51
Safe conversion? 4 19
This article will show, step by step, how to integrate R code into a R Sweave document
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now