문제

I wrote a program to output a random quote from a QStringList to a console window, program runs but I can't figure out why nothing appears in the window. Please help here is the code:

#ifndef RANDOMADVICE_H
#define RANDOMADVICE_H

#include <QString>
#include <QStringList>

class randomAdvice
{
public:
    randomAdvice();
    QString returnAdvice();

private:
    QStringList randomList;
    QString output;
};

#endif // RANDOMADVICE_H

here is the cpp file randomadvice.cpp

#include "randomadvice.h"
#include "cstdlib"
#include "ctime"
#include <QString>

randomAdvice::randomAdvice()
{
    randomList = QStringList()
                 << "In order to succeed, your desire for success should be greater than your fear of failure. - Bill Cosby"
                 << "Always be yourself, express yourself, have faith in yourself, do not go out and look for a successful personality and duplicate it. - Bruce Lee"
                 << "A successful man is one who can lay a firm foundation with the bricks others have thrown at him. - David Brinkley"
                 << "Strive not to be a success, but rather to be of value. - Albert Einstein"
                 << "To succeed in life you need 2 things: Ignorance and confidence. - Mark Twain"
                 << "Success is a lousy teacher. It seduces smart people into thinking they can't lose. - Bill Gates"
                 << "Remembering that you are going to die is the best way I know to avoid the trap of thinking that you have something to lose. You are already naked. There is no reason not to follow your heart. - Steve Jobs";
}

QString randomAdvice::returnAdvice()
{
    srand(time(NULL));
    output = randomList.at(rand() % randomList.size());
    return output;
}

and the main file:

#include "randomadvice.h"
#include <QtCore/QCoreApplication>
#include <QTextStream>


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream out(stdout);
    randomAdvice ra;
    QString adviceString = ra.returnAdvice();
    out << adviceString;
    return a.exec();
}
도움이 되었습니까?

해결책

QTextStream buffer the output until it is flushed or a newline is written.

You can either add out.flush() after out << adviceString or change out << adviceString to out << adviceString << endl.

다른 팁

Try QTextStream out(stdout, QIODevice::WriteOnly);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top