0

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();
}
Dmon
  • 220
  • 4
  • 15

2 Answers2

1

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.

deGoot
  • 996
  • 4
  • 11
0

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

RobbieE
  • 4,280
  • 3
  • 22
  • 36
  • Please include explanation of what your code does and how it answers the question. If you get a code snippet as an answer, you may not know what to do with it. Answer should give the OP guidance on how to debug and fix their problem. Pointing out, what the idea behind your code is, greatly helps in understanding the issue and applying or modifying your solution. – Palec Mar 31 '14 at 23:05