PDA

View Full Version : What am I doing wrong??



Splatify
7th February 2011, 06:37
Ok this is the (relevant) code i have:

quiz.cpp

void Quiz::on_NextButton_clicked()
{
QuizDialog question;
question.myfile.open("C:\\questions.txt");
if(question.myfile.is_open()){
question.next_question();
}

void Quiz::next_question(){
while(!(line=="<EOQ>")){
getline(myfile, line);
if(line == "<QUESTION_TEXT>"){
getline(myfile, line);
ui->QuestionLabel->setText(line.c_str());
qDebug() << "Question: " << line.c_str();
}
}

quiz.h

#ifndef QUIZ
#define QUIZ

#include <iostream>
#include <fstream>
#include <string>
#include <QDialog>
using namespace std;

namespace Ui {
class Quiz;
}

class Quiz : public QDialog
{
Q_OBJECT

public:
explicit Quiz(QWidget *parent = 0);
~Quiz();
ifstream myfile;
string line;
void next_question();

private:
Ui::Quiz *ui;


private slots:
void on_NextButton_clicked();
};


Ok so here's the problem. The file is opening fine. The function 'next_question();' then runs and "qDebug() << "Question: " << line.c_str();" does output the relevant information to the debugger.

However in the line above this, 'ui->QuestionLabel->setText(line.c_str());' i have asked for the caption on my form to be set to whatever the current value of line is. For some reason this does not seem to work. I know that the file is being access and I know that the correct line is being found. However I cannot output this information to the form. :( Could someone please explain what's up??


Thanks for your time and trouble. :)

Lykurg
7th February 2011, 07:16
Hi,

I guess, that because you call question.next_question(); in a loop, the last time line is empty and thus all other previous found strings are deleted since the label would only show the last one. (Or what exactly is the output of your program?)

Further since it seems you are using a XML file, you could have a look at QDomDocument.

ChrisW67
7th February 2011, 07:28
It is not at all obvious where "myfile" used in Quiz::next_question(), that is Quiz::myfile, is opened. QuizDialog::myfile, as used in on_NextButton_clicked(), is not related to Quiz::myfile.

In on_NextButton_clicked() the local variable "question" and its members (including one called myfile) ceases to exist at the end of the method. Typically destruction of a stream of file object would close the stream/file. We cannot be certain what is happening here because we don't know what type QuizDialog::myfile is.

Splatify
7th February 2011, 16:47
Thanks for the help... I think I have managed a work around. I'm now storing each line as a string and then outputting them to the ui once the next_question() function has finished.

Thanks for your time and trouble :D