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

}
2
  • How do you expect toString to display anything? It just returns a QString to the caller, nowhere in it you seem to mention any IO function. Commented Feb 12, 2016 at 6:52
  • Thank you Andreas. Bit of a blond moment :-) Commented Feb 12, 2016 at 7:11

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

It should probably be toLocal8Bit() instead of toUtf8() for this to work fine on Windows and older Linux.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.