0

I have a problem where I can't seem to get a output to display in a console when doing it through a function.

It works when doing it through Main(), but just blank when doing it through the function.

Below is some of my code:

#include "ConferencePaper.h"
#include "JournalArticle.h"
#include "Reference.h"
#include <QDebug>
#include <QTextStream>

QTextStream cout(stdout);

int main()
{
//QApplication app(argc, argv);
QStringList list1;
list1 << "This is a test";

Reference a("Marius",list1,1,"c"); //Instance of the Reference class created      with parameter values
cout << "Title: " << a.getTitle(); //This works fine
a.toString();

return 0;

}
//Reference Function

#include <QString>
#include <QStringList>
#include <QTextStream>
#include "Reference.h"

Reference::Reference(QString ti, QStringList as, int ye, QString id): title(ti), authors(as), year(ye), refID(id){}

QString Reference::toString()
{
return QString("Title: %1\n") .arg(getTitle()); //Does not display anything

}
Andreas Fester
  • 34,015
  • 7
  • 86
  • 113
mvanstad
  • 37
  • 3

2 Answers2

1

In your toString() method:

QString Reference::toString() {
  return QString("Title: %1\n") .arg(getTitle()); //Does not display anything
}

there is nothing which could cause to print anything on the console. You are simply returning the string as a result of that method.

To display something, you need to output the string which is returned from the method, e.g. in your main() function like

cout << a.toString().toUtf8().constData();

or

cout << a.toString().toLocal8Bit().constData();

Note that you need to convert your QString to a data type for which a << operator is available for ostream. See also How to convert QString to std::string?

Community
  • 1
  • 1
Andreas Fester
  • 34,015
  • 7
  • 86
  • 113
0

As mentioned above several times, X.toString(); would just return QString to a caller, then depending on what you're trying to achieve you may:

  • print it to console using cout << ...

  • print it to Application Output pane in your Qt Creator using qDebug() << ...

    (see QDebug Class reference for details, it's pretty common debugging technique)

Community
  • 1
  • 1