output to console of a random string list Qt - c++

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);

Related

Incomplete Type is not Allowed QApplication

I am learning C++ with Qt. I have installed Qt 5.15 and am using VS2019. I have the below code (as per an example in a textbook I am working through):
#include <QtGui>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QTextStream cout(stdout);
//declarations of variables
int answer = 0;
do{
//local variables
int factArg = 0;
int fact(1);
factArg = QInputDialog::getInt(0, "Factorial Calculator", "Factorial of:", 1);
cout << "User entered: " << factArg << endl;
int i = 2;
while (i <= factArg) {
fact = fact * i;
++i;
}
QString response = QString("The factorial of %1 is %2.\n%3").arg(factArg).arg(fact).arg("Do you want to compute another factorial?");
answer = QMessageBox::question(0, "Play again?", response, QMessageBox::Yes | QMessageBox::No);
} while (answer == QMessageBox::Yes);
return EXIT_SUCCESS;
}
However, I am recieving the below error when creating an instance of QApplication as app:
Incomplete Type is not Allowed
I am also recieving the below error for the QInputDialog and QMessageBox classes:
name followed by '::' must be a class or namespace name
I am not sure why this is happening - presumably something with a namespace, but I am not sure what scope to provide. I have searched the web but to no avail.
UPDATE
Adding the below header references give cannot open source file error for each.
#include <QApplication>
#include <QInputDialog>
#include <QMessageBox>
I have also added suggestions from the comments to my code, now below:
#include <QtGui>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QTextStream cout(stdout);
//declarations of variables
int answer = 0;
do{
//local variables
int factArg = 0;
int fact(1);
factArg = QInputDialog::getInt(0, "Factorial Calculator", "Factorial of:", 1);
cout << "User entered: " << factArg << endl;
int i = 2;
while (i <= factArg) {
fact = fact * i;
++i;
}
QString response = QString("The factorial of %1 is %2.\n%3").arg(factArg).arg(fact).arg("Do you want to compute another factorial?");
answer = QMessageBox::question(0, "Play again?", response, QMessageBox::Yes | QMessageBox::No);
} while (answer == QMessageBox::Yes);
return EXIT_SUCCESS;
}
But I am still recieving the same errors.
You have to include some qt headers in the app... that is the meaning of the message
you just need to add this to your code
#include <QApplication>
#include <QInputDialog>
#include <QMessageBox>
The correct headers to include are the following:
#include <QtWidgets/QApplication>
#include <QtWidgets/QInputDialog>
#include <QtWidgets/QMessageBox>
Once declaring these, the compiler accepts the code.
I'm going to cut and paste a working program for you.
Qt seems to have a bunch of forward definitions. I can tell I'm missing the right include file if I try to get the IDE to actually help me select a method call. In short, you pretty much have to #include every widget type or other class you're going to use. I haven't run into any shortcuts.
#include <QApplication>
#include "MainWindow.h"
using namespace std;
/**
* Main entry point.
*/
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}

Implementing a frontend for a c++ console application using QProcess

I am trying to implement GUI for a simple C++ using Qt to understand how it works. The C++ program and the GUI are in seperate projects in the same solution in VS 2015. The Qt program will call the C++ program using QProcess' start() function. The C++ console application will be running the background will the Qt program acts as an interface. My question is, how I do I pass values to the C++ program using QProcess and How do I obtain the output from the C++ program? Here is the sample program I am working with:-
The C++ Program
#include<iostream>
#include<fstream>
using namespace std;
void main() {
int a;
cout << "Enter a number" << endl;
cin >> a;
cout << "The Square of the number is " << (a*a) << endl;
ofstream write;
write.open("test.txt");
write << (a * a);
write.close();
}
The Qt Program
#include "FrontEnd.h"
#include <QtWidgets/QApplication>
#include <qprocess.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FrontEnd w;
w.show();
QProcess p1;
p1.start("Interface.exe");
p1.write("5",5);
return a.exec();
}
I tried to pass the value using the write() function but it did not seem to work as the test.txt file remained empty. The Qt program I have written lacks the GUI features as I will be adding them once I figure out how to send and recieve data using QProcess. Thank you for your assistance!
You have many problems in the code you are showing:
You are passing write two arguments "5" and 5, this means that it will use 5 chars from the the char* "5". Absolutely, this is not what you want as this will lead to undefined behavior resulted from accessing memory that does not belong to your data.
Instead you should be using the second version of write which accepts a zero-terminated string, like this: p1.write("5");
In order to make cin in your console program know that the number it should read is finished, you should pass a new line after your number, so your call will end up like this: p1.write("5\n");
You should use the readyRead signal in the Qt program to get notified when your process has new output that you can read, and then you may call readAll from a slot which is connected to that signal.
For completeness, Here is how your code should be:
interface.cpp
#include<iostream>
using namespace std;
void main() {
int a;
cin >> a;
//No need to use file output
//it is simpler and more appropriate to read the output from stdout
cout << "The Square of the number is " << (a*a) << endl;
}
The Qt program
#include <QApplication>
#include <QWidget>
#include <QProcess>
#include <QDebug>
#include "FrontEnd.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FrontEnd w;
w.show();
QProcess p1;
p1.start("Interface.exe");
p1.write("5\n");
QObject::connect(&p1, &QProcess::readyRead, [&p1](){
//output to qDebug, you may want to update some GUI component instead
qDebug() << p1.readAll();
});
return a.exec();
}

Why messages printed after closing main window in Qt C++?

With this code
#include "mainwindow.h"
#include <QApplication>
#include <iostream>
#include <QDir>
#include <QTextStream>
int main(int argc, char *argv[]){
QApplication a(argc, argv);
QTextStream out(stdout);
out << QDir::currentPath();
std::cout << "Why is that?";
MainWindow mainWindow;
mainWindow.show();
return a.exec();
}
Both messages printed only after closing Main Window of my app, why is this?
I tried to debug, debugger thinks that he done with this line, but I see no messages.
extern std::ostream cout; is buffered, so it may choose when to flush its buffer to stdout. In your case, it is doing it when your program is terminating.
You can tell std::ostream to flush using std::flush, as such:
std::cout << "Why is that?" << std::flush;

No output display in console when running a function

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
}
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?
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)

QPixmap does not open some image

It opens one JPEG image but not the other JPEG. The directories and files exist on my system. For ease of recreation the images used in the below code are console test and f2.
#include "mainwindow.h"
#include <QApplication>
#include <QPixmap>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QPixmap *pixmap = new QPixmap;
pixmap->load("C:/Programs/console test.jpg");
if(pixmap->isNull())
cout << "darn" << endl;
else
cout << "not null" << endl;
pixmap->load("C:/Programs/f2.jpg");
if(pixmap->isNull())
cout << "darn" << endl;
else
cout << "not null" << endl;
return a.exec();
}
The above code prints
darn
not null
If relevant, the application is a QWidget application.
console test.jpg is actually a PNG file. – Oktalist
Oktalist answered the question. I naively used and changed the extension from png to jpg expecting file conversion. After undoing the change with the same method, the image successfully opens.
ifstream src("console print.jpg", ios::binary);
ofstream dest("console print.png", ios::binary);
dest << src.rdbuf();
dest.flush();
And now console print has the correct file extension. And it opens. There are a billion other ways you could do this, but this one was easy.
-Sanfer