hey guys,

I have this

RiddleGenerator::QnA RiddleGenerator::mQnA[RiddleGenerator::QuestionCount] = {
        { "What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square", 3 },
        { "What is the capital of England?\n\t1)Paris\n\t2)London\n\t3)Washington", 2 }

        // NEW QUESTIONs CAN GO IN THE ABOVE SPACE <---!
};

and have looked on the net but cant find anything helpful so here i am.

I wish to be able to load those questions and answers from a text file so for the user they can go into the text file and add and remove questions.

Just wondering how i could go about this as I cant get the standard variable export import workign with it

Thanks in advance

Darryl

Recommended Answers

All 23 Replies

which language do you want to achieve this?

We have no clue what that code is you posted, so can't help you very much.

>>Just wondering how i could go about this as I cant get the standard variable export import working with it

Is this going into a DLL? What is it that you want to export? Your question is just too vague.

Well we are in a cpp forum so im assuming im using cpp .....

And no it is source code.

I want to load the questions in the struct from a text file so that the person i give it too can edit the questions wihtout having to go into the source code and recompile ...

Yes, I know what you want to do, but what you posted isn't much help because we don't know what that structure looks like. You will have to design a file format for your users to follow when creating the text file then write the program to follow that format when reading the file. Its really not all that difficult a coding task once you have designed the file format like you want it.

Thats the part im stuck with, does the code depend on the file structure or does the file have to be written in a certain format.

Say I wanted the question like this in the file

Question Answer
Question Answer

E.g

What is the captial of london? 1

I'd have a struct like this:

struct quizQuestion
{
    string question;
    vector <string> possibleAnswers;
    string correctAnswer;
};

Then have a vector of quizQuestion that makes up the quiz.

Hmm... well Ill upload my file, so it is easier to see what I have.

Hmm... well Ill upload my file, so it is easier to see what I have.

Well, it's nothing like how I would have designed it. It looks like here is your struct:

struct QnA {
        string question;
        int answer;
    };

question includes the question and all of the answers. answer is the index of the correct answer. That means you have to parse this INTO something similar to mine.

"What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square"

Or maybe you don't. You can display this string as is and if the user answers with a number, you don't have to parse it at all. Helps with the display, but I prefer my setup. It gives you more options.

In order to proceed with how to read from a file, you'll have to design a sample file and post it. Either that file will start in the form of the struct or you'll have to turn it into the form of the struct (i.e. add a bunch of "\n\t" strings to your larger string.

I am new-ish to cpp so i just did it by the only way i knew how. its a random question generator.

here is a sample file format, im guessing this format would be easiest, if not please correct me, this is only part im stuck on

and i dont know how simple it would be and produce the same functionality if i change it,.

I am new-ish to cpp so i just did it by the only way i knew how. its a random question generator.

here is a sample file format, im guessing this format would be easiest, if not please correct me, this is only part im stuck on

and i dont know how simple it would be and produce the same functionality if i change it,.

How many sides to squares have? op1 op2 op3 answer

That's not a good idea IMO. You need to know when the question stops (presumably with a question mark, so that's easy, but can you assume that?). How do you know when option 1 stops and option 2 starts? Can you assume every option is one word? How do you know how many questions there are? How many options there are in a question? You need to think about all of this. One method:

3  // 3 questions
What is the capital of California?  // Question 1
2  // 2 options
Sacramento // option 1
San Antonio  // option 2
1  // correct answer (option 1 - Sacramento
What is the capital of New York?  // Question 2
3  // 3 options
Sacramento // option 1
San Antonio  // option 2
Albany // option 3
3  // correct answer (option 3 - Albany)
What is the capital of Florida?  // Question 3
4  // 4 options
Sacramento // option 1
San Antonio  // option 2
Tallahassee // option 3
Denver  // option 4
3  // correct answer (option 3 - Tallahassee)

Everything including and after // is a comment. Don't put that in the file (or treat // as a delimiter).

One answer or option per line. Hence you can have multiple word questions/answers. The numbers tell you how many questions/answers you have. You can use them in for-loops when you read in the data. Read it in and turn it into a format your struct can use.

Here is a simple idea.

1. Arrange your strings in the text file so that the program can easy parse the strings into questions and options (e.g. separate them by line)

2. Define struct to store your set of questions and options (e.g. there are some examples already posted)

3. Create a vector of this struct to store the set of questions and options as your read them from the text file. Remember, you do not know the number of questions in the text file. Using vector is a good idea.

4. As for the part of randomly generating question from the set, you may use a random number generator (e.g. srand function) to select the question from the vector. Make sure the number generate is within the boundary of vector size. (you can do this by using modulus)

Hope this helps...


Regards,
Nick

I see, i think, I still do not konw to get this from a text file into the place where i have them in my code (sorry about my english i am 2nd langauge )

I see, i think, I still do not konw to get this from a text file into the place where i have them in my code (sorry about my english i am 2nd langauge )

The question is too vague to answer. Which part of that are you having problems with? You need to pick a file format and use an ifstream to read it in.

The bit i stuck with is how to read it from a text file...

i dont know how to read it from a text file and make it work with the code i have

Here is one way to do it. Make sure the list is separated by tabs, not spaces. You could also make it a comma-separated list and this word work with it too if you replace '\t' with ','

What this does is build a vector of questions. Each Question class contains a vector of answers. By using this method the file can have an unlimited (almost) number of questions, and each question can have an unlimited (almost) number of answers.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
#pragma warning(disable: 4996)


class Question
{
private:
    string q;
    vector<string> answers;
public:
    Question(string& line);
    Question();
    string GetQuestion() {return q;}
    vector<string>& GetAnswers() {return answers;}
};

Question::Question(string& line)
{
    string word;
    stringstream str(line);
    // extract the question
    getline(str,this->q,'\t');
    // now extract each of the answers
    while( getline(str, word, '\t') )
    {
        if( word.length() > 0)
            answers.push_back(word);
    }
}

int main()
{
    string line;
    ifstream in("file.txt");
    vector<Question> questions;
    if( in.is_open() )
    {
        while( getline(in, line) )
        {
            Question q(line);
            questions.push_back(q);
        }

    }
}

hmmmm well i try to ee if i can fit something like that into my code, i cant just change it like that coz it to complicated and threaded in with other code

// The C++ Adventure Game Version 3.
// Year 12 I.T :: Mr Haughton :: 2009
// Darryl Mitchell
// Aliaks Inc. All Rights Reserved.


#ifndef QUESTION_MATH_RIDDLE_GENERATOR_H_INCLUDED
#define QUESTION_MATH_RIDDLE_GENERATOR_H_INCLUDED

#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include <stdio.h>
#ifdef WIN32
#include <Windows.h>
#define snprintf _snprintf
#endif

#define PROGRAMMING_ERROR std::cerr << "Programming error at " << __FILE__ << " line " << __LINE__ << std::endl;

using namespace std;

static int randBetween(int low, int high)
{
    if (low == high) return low;
    if (low > high)
    {
        int tmp = low;
        low = high;
        high = tmp;
    }

    static bool firstTime = true;
    if (firstTime)
    {
        srand((unsigned int)time(NULL));
        firstTime = false;
    }
    int num = rand();
    int result = num % (high - low + 1) + low;
    return result;
}

class QuestionGenerator
{
    /*
    Defines the public interface to question generators
    */
public:
    virtual const string& poseQuestion(void) = 0;
    virtual bool isCorrectAnswer(const std::string& answer) const = 0;
};

class ArithmeticQuestionGenerator: public QuestionGenerator
{
    /*
    Creates arithmetic question
    */
public:

    virtual const string& poseQuestion(void)
    {
        Operation operation = (Operation)randBetween(ADD, SUBT);

        // THIS IS WHERE YOU CHANGE THE NUMBERS.
        //
        // Operand1 = randBetween(A, B);
        // Operand2 = randBetween(C, D);
        //
        // A >= D
        // B >  A
        // C <= D
        // D >  D
        //
        // If you want positive and predictable outcomes.

        int operand1 = randBetween(0, 50);
        int operand2 = randBetween(0, 25);


        char buf[128];
        snprintf(buf, sizeof(buf), "What is %d %c %d ?",
            operand1, operationChar(operation), operand2);
        mCurrentQuestion = buf;

        switch(operation)
        {
        case ADD:
            mAnswer = operand1 + operand2;
            break;
        case SUBT:
            mAnswer = operand1 - operand2;
            break;
        default:
            PROGRAMMING_ERROR;
        }
        return mCurrentQuestion;
    }

    virtual bool isCorrectAnswer(const std::string& answer) const
    {
        return (atoi(answer.c_str()) == mAnswer);
    }

private:
    enum Operation
    {
        ADD = 1,
        SUBT
    };

    char operationChar(Operation op) {
        switch(op)
        {
        case ADD:
            return '+';
        case SUBT:
            return '-';
        default:
            PROGRAMMING_ERROR;
            break;
        }
        return ' ';
    }

    string mCurrentQuestion;
    double mAnswer;
};

class RiddleGenerator: public QuestionGenerator
{
public:
    /*
    Trivial pursuit questions
    */
    virtual const string& poseQuestion(void)
    {
        int q = randBetween(0, QuestionCount-1);
        mAnswer = mQnA[q].answer;
        return mQnA[q].question;
    }

    virtual bool isCorrectAnswer(const string& answer) const
    {
        return (atoi(answer.c_str()) == mAnswer);
    }

private:
    struct QnA {
        string question;
        int answer;
    };

    static const int QuestionCount = 2;
    static QnA mQnA[QuestionCount];
    int mAnswer;
};

// THIS IS WHERE YOU INSERT QUESTIONS.
//
// The structure MUST remain the same
//
// { "QUESTION?\n\t1)CHOICE1\n\t2)CHOICE2\n\t3)SO ON", The Number which relates to the ANSWER }

RiddleGenerator::QnA RiddleGenerator::mQnA[RiddleGenerator::QuestionCount] = {
        { "What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square", 3 },
        { "What is the capital of England?\n\t1)Paris\n\t2)London\n\t3)Washington", 2 }

        // NEW QUESTIONs CAN GO IN THE ABOVE SPACE <---!
};

class QuizMaster : public QuestionGenerator
{
    /*
    Responsible for holding different types of question generators
    */
public:
    QuizMaster()
    {
        mCurrentQuestionGenerator= NULL;
        mGenerators.push_back(new RiddleGenerator());
        mGenerators.push_back(new ArithmeticQuestionGenerator());
    }

    virtual const string& poseQuestion(void)
    {
        int ix = randBetween(0, int(mGenerators.size()-1));
        mCurrentQuestionGenerator = mGenerators[ix];
        return mCurrentQuestionGenerator->poseQuestion();
    }

    virtual bool isCorrectAnswer(const std::string& answer) const
    {
        if (mCurrentQuestionGenerator == NULL) return false;
        return mCurrentQuestionGenerator->isCorrectAnswer(answer);
    }

    vector<QuestionGenerator*> mGenerators;
    QuestionGenerator* mCurrentQuestionGenerator;
};

#endif // QUESTION_MATH_RIDDLE_GENERATOR_H_INCLUDED

reckon it can fit into this format coding?

This code has the questions written in ( WHICH I WANT TO LOAD FROM TEXTFILE SOMEOUT ) and randomly picks the question, and also reandomly generates number questions and then picks a question out of these 2 options when the function is called.

What do you mean when you talk about whether it will "fit into" your code? Is there some maximum size for the code? You're not planning on having the executable program and the text file actually CHANGE the source code by somehow inserting the text file questions into the C++ program source code, are you? If you are, then you can ignore all my posts so far because I wasn't assuming that at all and I seriously doubt that's what you're supposed to do.

What do you mean when you talk about whether it will "fit into" your code? Is there some maximum size for the code? You're not planning on having the executable program and the text file actually CHANGE the source code by somehow inserting the text file questions into the C++ program source code, are you? If you are, then you can ignore all my posts so far because I wasn't assuming that at all and I seriously doubt that's what you're supposed to do.

Sorry, this is the brother of the author, I understand English much better.

See the struct where the questions are held.

RiddleGenerator::QnA RiddleGenerator::mQnA[RiddleGenerator::QuestionCount] = {
        { "What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square", 3 },
        { "What is the capital of England?\n\t1)Paris\n\t2)London\n\t3)Washington", 2 }

        // NEW QUESTIONs CAN GO IN THE ABOVE SPACE <---!

Instead of having it preset by the programmer, he is wondering if he can load these questions from a text file.

Example: If he compiles this and gives it to a teacher, they can open the QnA.txt and add and edit there own questions and answers, as long as they keep what ever format the program he compiles is able to read.

As for changing the source code externally, negitive. He only wishes to edit the questions by making the program read the struct data from a text file rather than him writing in the questions and the user not being able to change them without having the source code.

The nature of his code is a random question generator. He has rooms connected together and each time the user moves to a different room, this function is called:

quizMaster.poseQuestion().c_str()

Now this randomly picks between the question genorater ( which produces a random number question , e.g. 20-10 = ) or the riddle genorater, which randomly choses a question fro the struct, which is the part his question relatess to.

I hope that clarifies what he is asking, if this doesnt please inform me and I will do my best to explain,

Regards,

Carlos

Sorry, this is the brother of the author, I understand English much better.

See the struct where the questions are held.

RiddleGenerator::QnA RiddleGenerator::mQnA[RiddleGenerator::QuestionCount] = {
        { "What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square", 3 },
        { "What is the capital of England?\n\t1)Paris\n\t2)London\n\t3)Washington", 2 }

        // NEW QUESTIONs CAN GO IN THE ABOVE SPACE <---!

Instead of having it preset by the programmer, he is wondering if he can load these questions from a text file.

Example: If he compiles this and gives it to a teacher, they can open the QnA.txt and add and edit there own questions and answers, as long as they keep what ever format the program he compiles is able to read.

As for changing the source code externally, negitive. He only wishes to edit the questions by making the program read the struct data from a text file rather than him writing in the questions and the user not being able to change them without having the source code.

The nature of his code is a random question generator. He has rooms connected together and each time the user moves to a different room, this function is called:

quizMaster.poseQuestion().c_str()

Now this randomly picks between the question genorater ( which produces a random number question , e.g. 20-10 = ) or the riddle genorater, which randomly choses a question fro the struct, which is the part his question relatess to.

I hope that clarifies what he is asking, if this doesnt please inform me and I will do my best to explain,

Regards,

Carlos

Okay, that's what I had in mind with my earlier responses. Yes, he can do this. I assume he didn't write any of the code he posted? He needs to have a main () function, as all executable programs do. I don't see one posted. He needs to include the fstream library and set up an ifstream object to read from the file. I don't see either of these things. Without the main () function, it's hard to tell how he wants to use the code that he posted. the struct that he is stuck with is this:

struct QnA {
        string question;
        int answer;
    };

That's been given to him and he's not allowed to change that. The format of question must eventually be this:

What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square

This too has been specified by the code that's already been written/posted.

If he chooses to use a file like the one I suggested earlier, he would need to read it in and CONVERT it to this format. That's what I would recommend probably. There's going to be some conversion no matter what.

The big question is how much of the code that he posted does he understand? If he doesn't understand what he posted and he doesn't know what his overall goal is for the main program, then he can't really write the part that reads in from the file. Has he used fstream and the ifstream library before? If not, he should take a tutorial on it before attempting this. He said he was a beginner, but didn't elaborate.

Note that if you were to create a text file with questions in it, you wouldn't type in a "\n" and "\t". Those are invisible characters (ENTER key and tab key), so don't just copy and paste them into the text file.

My advice would be to get it to work WITHOUT reading from the file first. So we need a main () function of some kind. Then when you have that working, work on reading in from a file. But it's hard to get a feel for it without a driver program/main function.

That has indeed been done, he only posted the part revelent to posting, now I have no idea what any of this means, I am only the language person, but he said he does not know how to utilize fstream I/O with the struct.

He said also he did right most this code and here is the rest (including the main for you)
main.cpp

// The C++ Adventure Learning Game Version 3.

#include "classes.h"
#include <Windows.h>
#include "Question_Math_Riddle_Generator.h"

#include <string>
#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include <stdio.h>
#include <fstream>
#ifdef WIN32

#define snprintf _snprintf
#endif

#define PROGRAMMING_ERROR std::cerr << "Programming error at " << __FILE__ << " line " << __LINE__ << std::endl;

using namespace std;

// GLOBAL VARIABLES. //

int iUserPoints = 200, iWrongAnswer = 10, iRightAnswer = 10, iFinishBonus = 1000, iPlayerLives = 10, iLiveBonus = iPlayerLives * 100;

//




int main(int argc, char **argv)
{
//-------------- ROOM NAME START ---------------//
//----------------------------------------------//

	Room *rooms = new Room [42];
	rooms[0].name = "Crossroads";
	rooms[1].name = "Bridge";
	rooms[2].name = "The Ancient Gate";
	rooms[3].name = "Cut Thoat Path";
	rooms[4].name = "Rockledge";
	rooms[5].name = "Rockface Markings";     // Pz
	rooms[6].name = "Glade";
	rooms[7].name = "Cave";
	rooms[8].name = "Small opening";
	rooms[9].name = "Cavern";
	rooms[10].name = "The Sunken Temple";    // Pz
	rooms[11].name = "Ledge";
	rooms[12].name = "The Great Drop";       // DE
	rooms[13].name = "Tunnel";
	rooms[14].name = "Cave Exit";
	rooms[15].name = "Marsh";
	rooms[17].name = "The Burning Circle";
	rooms[18].name = "The Silver Vein";      // DE
	rooms[19].name = "The Jump";
	rooms[20].name = "The Waterfall";
	rooms[21].name = "Secundum Lacrima";     // Pz
	rooms[22].name = "The Rocky Plains";
	rooms[23].name = "Wastelands";
	rooms[24].name = "The Sink hole";
	rooms[25].name = "The Slagpit";          // Pz
	rooms[26].name = "The Beach of Ends";    // DE
	rooms[27].name = "Infinitio Versus";     // DE
    rooms[28].name = "Mountain Wall";        // Pz
	rooms[29].name = "The Valley";
	rooms[30].name = "The Dunes";
	rooms[31].name = "Booty Beach";
	rooms[32].name = "The Lost Shrine";
	rooms[33].name = "Isle";                 // DE
	rooms[34].name = "The Underpass";
	rooms[35].name = "Rockfall";
	rooms[36].name = "Pools of Angmar";      // Pz // To waterfall
	rooms[37].name = "Windy Cross Road";
	rooms[38].name = "The Overlook";         // Pz
	rooms[39].name = "Whispering Pass";
	rooms[40].name = "Demonic Alter";        // DE
    rooms[41].name = "The Encampment";       // DE

//--------------- ROOM NAME END ----------------//
//----------------------------------------------//

//-------------- ROOM NAME START ---------------//
//----------------------------------------------//

/* CROSSROADS */	    rooms[0].description = "You arrive at a barrenness area. Small scrubs are scattered amongst the warm\nsands. Ahead of you a scorched wooden signpost rises lazily out of a ground.\nIt reads: ";
/* BRIDGE */	        rooms[1].description = "A river is flowing gracefully through a huge hole in the ground. You notice\na wooden bridge to your right, it appears to be safe.";
/* ANCIENT GATES */	    rooms[2].description = "Two enormous pillars rise up from the sands and appear to form a gate.\nThere are ancient symbols written over the columns which gives it a creepy\nbut magical feel.";
/* CUT THROAT PATH */ 	rooms[3].description = "The warm sands fade away into solid rock, the horizon splits into two\nrock faces. """"CUT THOAT"""" is painted across one of the faces." ;
/* ROCKLEDGE */     	rooms[4].description = "You climb the face of the rock and find yourself walking along a small strip of\nflat rock, it seems to lead to nothing.";
/* ROCKFACE MARKINGS */ rooms[5].description = "Rockface Markings";
/* GLADE */	            rooms[6].description = "The path between the faces splits into a small glade surrounded by palm trees\nwhich is very strange considering the location. You notice a small cave \non the other side.";                 //
/* CAVE */	        	rooms[7].description = "The light is very dim, it seems others have ventured through here before.\nThe passage is lit by small lanterns. You notice a small crack in the\nwall along the tunnel.";
/* SMALL OPENING */	    rooms[8].description = "After much twisting and turning you are able to force your way through\nthe small gap.";
/* CAVERN */	        rooms[9].description = "After crawling through the darkness you arrive at a large cavern.\nWhat appears to be a stone chair is placed in the middle of the cavern\nsurrounded by water.";
/* SUNKEN TEMPLE */	    rooms[10].description = "Statues of Kings and Queens carved from stone allign the walls. What appears to be the\nruins of a lost temple covered in moss and grime lays before you. You walk\nknee deep in dirty water with big sloshes.";
/* LEDGE */	            rooms[11].description = "Ledge";
/* GREAT DROP */	    rooms[12].description = "The rock breaks away into darkness and crumbles under your feet as you look down.\nYou can see nothing but empty space and have no idea where the hole leads but\nyou don't really want to know.";
/* TUNNEL */        	rooms[13].description = "Glow worms light up the tunnel like street lights. You can see bugs crawling along\nthe tunnel like crawling ants.";
/* CAVE EXIT */     	rooms[14].description = "A room like shape is carved into the rock. A large opening cuts the wall.\nOn the opposite side of the room, a tunnel leads off into the darkness.";
/* MARSH */         	rooms[15].description = "A huge slope builds on one side of the marsh. Below the ground looks muddy\nand unstable. The marsh is like a maze of land and dirty dark water.\n'One wrong step and I could be going for a swim!' you think to yourself. ";
/* FOREST */ 	        rooms[16].description = "The trees are tall, slender and sway gently in the breeze. As you look further\ninto the forest the shadows darken and create monsterous looking\nfigures.";
/* BURNING CIRCLE */	rooms[17].description = "After much adventuring you arrive at a circular opening.\nIn the centre is a pile of old trees which appear to have been burnt once.\nDebris is scattered all over the place.";
/* SILVER VEIN */   	rooms[18].description = "The Silver Vein";
/* JUMP */          	rooms[19].description = "The wind whips across your face. You look around and see nothing but a huge drop.\nPainted on a small plank of wood reads 'One way travel'. You see a\nwaterfall in the distance, you are quite thirsty. ";
/* WATERFALL */         rooms[20].description = "You cup the water in your hands and take a drink. As you raise your head\nyou see something shining through the waterfall, curious. Your eyes pass/nthe waterfall and fall on some trees in the distance.";        // WATFERFALL
/* SECUNDUM LACRIMA ( THROUGH THE WATERFALL ) */
                        rooms[21].description = "Water splashes against the rocks to form a pool. The rocks build up into\na pedistal and a golden box sits on it, shining gracefully.";
/* ROCKY PLAINS */	    rooms[22].description = "There are rocks scattered everywhere and not one organic thing is in sight,\nyou doubt anything could live here.";
/* WASTELANDS */	    rooms[23].description = "Bones of dead animals lay all over the place. You see what appears to be\ndark holes scattered like a dalmation. On closer inspection you notice that\nthey are pools of oil, much like the ones that captured mammoths in the\ndinosaur age.";
/* SINKHOLE */	        rooms[24].description = "The hole is wet and grimy, its like a sludgey monster could jump out at you\nat any second. The surrounding area is dark and nothing but water drops can be heard.";
/* SLAGPIT */	        rooms[25].description = "The Slagpit";
/* BEACH OF ENDS */	    rooms[26].description = "The sand is soft on your feet and is pure white, the ocean is a clear\naqua blue with gentle waves crashing against the beach. The beach is perfect,\nmaybe one day you can return after your adventures";
/* INFINITIO VERSUS ( THE MIRAGE  ) */
                        rooms[27].description = "You feel the heat on the back of your neck, it is unbelieveably warm,\nyou can't stand the heat. You see a town in the distance; they must have water\nand shade.";
/* MOUNTAIN WALL */     rooms[28].description = "The wall is very smooth, you can make out some rough parts you might be able\nto grab onto.";
/* THE VALLEY */	    rooms[29].description = "The ground lowers into a valley full of flowers and greenary.\nIt is full of wildlife from butterflies to fluffy rabbits. Across the\nValley you can see sand creeping its way in. ";
/* THE DUNES */         rooms[30].description = "Great mounds of sand reach outwards towards the sky, you can see the tracks of sand snakes.\nBetter be careful! You can hear the crashing of waves in the distanace. ";
/* THE BEACH */      	rooms[31].description = "An old sled slants lazily in the summer shine. A signpost swings from the roof\nof the shed in the breeze. 'Booty Beach Cafe' You look across\nthe beach and see what looks to be a circular platform on the water. ";
/* LOST SHRINE */ 	    rooms[32].description = "A stone bowl sits in the centre of the circular wooden platform. A clear\nliquid sloshes slightly as the platform moves with the waves. You have no\nidea what you are meant to do here, maybe time will tell. ";
/* ISLE */	            rooms[33].description = "Isle";
/* UNDERPASS */	        rooms[34].description = "?";
/* ROCKFALL */     	    rooms[35].description = "Rockfall";
/* POOLS OF ANGMAR */	rooms[36].description = "A series of pools connect along a dirty path as far as the eye can see.\nGlowing orbs levitate above the pools surface which luminates the liquid below." ;
/* WINDY CROSS ROAD */	rooms[37].description = "The wind is strong and the sun is even stronger. The path cuts deeply into\nthe side of the mountain and slowly climbs towards the top.";
/* OVERLOOK */	        rooms[38].description = "You can see the entire region of Shinnoh, the smoke from Aliaksiam and ...\nwhat is that, an encampment! Maybe the Princess is there?!";
/* WHISPERING PASS */   rooms[39].description = "A strange noise bounces back and fourth off the walls of the cavern, the noise is like whispering voices that never stop.\nAs you pass through the pass you feel like someone is looking over your back.";
/* DEMONIC ALTER */	    rooms[40].description = "A stone slab splashed with blood lays between dozens of candles which have melted down to stubs. Strange symbols much like\nones found on the Gate are carved into it. Along the side a word is set with jewels, EKYU.";
/* ENCAMPMENT */        rooms[41].description = "The Encampment";

//--------------- ROOM NAME END ----------------//
//----------------------------------------------//



//----------- ROOM CONNECTIONS START -----------//
//----------------------------------------------//

	// Crossroads
	//---------------------------//
	// To's
	rooms[0].west = &rooms[1];   // Bridge
	rooms[0].south = &rooms[2];  // The Ancient Gate
	rooms[0].east = &rooms[3];   // Cut Thoat Path
    // Back's
    rooms[1].east = &rooms[0];   // Bridge
	rooms[2].north = &rooms[0];  // The Ancient Gate
	rooms[3].west = &rooms[0];   // Cut Thoat Path
	//---------------------------//

    // Cut Thoat
	//---------------------------//
	// To's
	rooms[3].east = &rooms[6];   // Glade
	rooms[3].north = &rooms[4];  // Rockledge
    // Back's
    rooms[6].west = &rooms[3];   // Glade
	rooms[4].south = &rooms[3];  // Rockledge
	//---------------------------//

    // Glade
	//---------------------------//
	// To's
	rooms[6].north = &rooms[7];  // Cave
    // Back's
    rooms[7].south = &rooms[6];  // Cave
	//---------------------------//

    // Cave
	//---------------------------//
	// To's
	rooms[7].north = &rooms[8];  // Small Opening
	rooms[7].east = &rooms[13];  // Tunnel
    // Back's
    rooms[8].south = &rooms[7];  // Small Opening
    rooms[13].west = &rooms[7];  // Tunnel
	//---------------------------//

    // Small Opening
	//---------------------------//
	// To's
	rooms[8].west = &rooms[9];   // Cavern
	rooms[8].east = &rooms[11];  // Ledge
    // Back's
    rooms[9].east = &rooms[8];   // Cavern
    rooms[11].west = &rooms[8];  // Ledge
	//---------------------------//

    // Tunnel
	//---------------------------//
	// To's
	rooms[13].east = &rooms[14]; // Cave Exit
	rooms[13].west = &rooms[6];  // Glade
    // Back's
    rooms[13].west = &rooms[14]; // Cave Exit
    rooms[13].east = &rooms[6];  // Glade
	//---------------------------//

    // Cave Exit
	//---------------------------//
	// To's
	rooms[14].south = &rooms[15];// Marsh
	rooms[14].east = &rooms[23]; // Wastelands
    // Back's
    rooms[15].north = &rooms[14];// Marsh
    rooms[23].west = &rooms[14]; // Wastelands
	//---------------------------//

    // Wastelands
	//---------------------------//
	// To's
	rooms[23].east = &rooms[27]; // The Mirage
	rooms[23].south = &rooms[24];// Sinkhole
    rooms[24].west = &rooms[26]; // The Beach of Ends
    // Back's
    rooms[27].west = &rooms[23]; // The Mirage
    rooms[24].north = &rooms[23];// Sinkhole
    rooms[26].west = &rooms[24]; // The Beach of Ends
	//---------------------------//

    // The Mirage
	//---------------------------//
	// To's
	rooms[27].east = &rooms[27]; // Itself, so It appears a constant walk to no-where.
	//---------------------------//

    // Marsh
	//---------------------------//
	// To's
	rooms[15].south = &rooms[16];// Forest
    // Back's
    rooms[16].north = &rooms[15];// Forest
	//---------------------------//

    // Forest
	//---------------------------//
	// To's
	rooms[16].west = &rooms[17]; // The Burning Circle
	rooms[16].south = &rooms[20];// The Waterfall
	rooms[16].east = &rooms[41]; // The Encampment
    // Back's
    rooms[17].east = &rooms[16]; // The Burning Circle
    rooms[20].north = &rooms[16];// The Waterfall
    rooms[41].west = &rooms[16]; // The Encampment
	//---------------------------//

    // The Burning Circle
	//---------------------------//
	// To's
	rooms[17].west = &rooms[18]; // The Silver Vein
	rooms[17].east = &rooms[19]; // The Jump
    // Back's
    rooms[18].east = &rooms[17]; // The Burning Circle
    rooms[19].west = &rooms[17]; // The Jump
	//---------------------------//

    // The Jump
	//---------------------------//
	// To's
	rooms[19].east = &rooms[20]; // Jump to the waterfall
    // Back's
    //                           // Cannot jump back up . . .
	//---------------------------//

    // The Ancient Gate
	//---------------------------//
	// To's
	rooms[2].west = &rooms[28];  // The Mountain Wall
	rooms[2].south = &rooms[39]; // Whispering Pass
    rooms[2].east = &rooms[37];  // Windy Cross Road
    // Back's
    rooms[28].east = &rooms[2];  // The Mountain Wall
    rooms[39].north = &rooms[2]; // Whispering Pass
    rooms[37].west = &rooms[2];  // Windy Cross Road
	//---------------------------//

    // Bridge
	//---------------------------//
	// To's
	rooms[1].east = &rooms[28];  // The Mountain Wall
	rooms[1].south = &rooms[29]; // The Valley
    // Back's
    rooms[28].west = &rooms[1];  // The Mountain Wall
    rooms[29].north = &rooms[1]; // The Valley
	//---------------------------//

    // The Valley
	//---------------------------//
	// To's
	rooms[29].east = &rooms[30]; // The Dunes
	rooms[29].south = &rooms[34];// The Underpass
    // Back's
    rooms[30].west = &rooms[29]; // The Dunes
    rooms[34].north = &rooms[29];// The Underpass
	//---------------------------//

    // The Dunes
	//---------------------------//
	// To's
	rooms[30].east = &rooms[33]; // The Isle
	rooms[30].south = &rooms[31];// Booty Beach
    // Back's
    rooms[33].west = &rooms[30]; // The Dunes
    rooms[31].north = &rooms[30];// The Underpass
	//---------------------------//

    // The Underpass
	//---------------------------//
	// To's
	rooms[34].south = &rooms[36];// Pools of Angmar
	rooms[34].east = &rooms[35]; // Rockfall
    // Back's
    rooms[36].north = &rooms[34];// Pools of Angmar
    rooms[35].west = &rooms[34]; // Rockfall
	//---------------------------//

    // Booty Beach
	//---------------------------//
	// To's
	rooms[31].south = &rooms[32];// The Lost Shrine
    // Back's
    rooms[32].north = &rooms[31];// The Lost Shine
	//---------------------------//

    // Pools of Angmar
	//---------------------------//
	// To's
	rooms[36].east = &rooms[20]; // The Waterfall
    // Back's
    rooms[20].west = &rooms[36]; // The Waterfall
	//---------------------------//

    // Rockfall
	//---------------------------//
	// To's
	rooms[35].east = &rooms[41]; // Encampment
    // Back's
    rooms[41].west = &rooms[35]; // Encampment
	//---------------------------//

    // Waterfall
	//---------------------------//
	// To's
	rooms[20].south = &rooms[22];// Rocky Plains
    rooms[20].east = &rooms[21]; // Secundum Lacrima
    // Back's
    rooms[22].north = &rooms[20];// Rocky Plains
    rooms[21].west = &rooms[20]; // Secundum Lacrima
	//---------------------------//

    // Rocky Plains
	//---------------------------//
	// To's
	rooms[22].east = &rooms[41]; // Encampment
    // Back's
    rooms[41].west = &rooms[22]; // Encampment
	//---------------------------//

    // Whispering Pass
	//---------------------------//
	// To's
	rooms[39].east = &rooms[38]; // Overlook
	rooms[39].west = &rooms[40]; // Demonic Alter
    // Back's
    rooms[38].west = &rooms[39]; // Overlook
	//---------------------------//

    // Windy Cross Road
	//---------------------------//
	// To's
	rooms[37].east = &rooms[38]; // Encampment
    // Back's
    rooms[38].west = &rooms[37]; // Encampment
	//---------------------------//

    // The Overlook
	//---------------------------//
	// To's
	rooms[38].south = &rooms[41];// Whispering
    // Back's
    rooms[41].north = &rooms[38];// Whispering
	//---------------------------//


//------------ ROOM CONNECTIONS END ------------//
//----------------------------------------------//


//-------------------------- GAME START ----------------------------//
//------------------------------------------------------------------//

    User NewUser;               //Create a User class
    string sTempUserName;       //Create a temporary variable for input
    int iTempAge;               //Create a temporary variable for input
    string sAgeInput;
    int iPetChoice;
    string sPlayerInPet;
    string sHelpAnswer;
    char cHelpAnswer;

    QuizMaster quizMaster;
    string answer;

    cout << "Welcome to the Knight of Aliaksiam by Darryl Mitchell" << endl;

    cout << "\nEnter your desired username: " << endl;
    getline(cin,sTempUserName);                         // Store the user input in the temporary variable
    cout << "\nAnd now your Age: " << endl;
    getline(cin,sAgeInput);	                            // Grab everything in the buffer, even if it's more than one character.

    iTempAge = sAgeInput[2];	                        // Only use the first three characters, discard the rest.

    cout << "\nNo great adventurer is complete without their trusty companion! \nWhich do you have?  A Dog, Cat or an Eagle? ";

    iPetChoice= 0;
//------------------------------------------------------------------------------------------------------------------------// START   //
    do {                                                                                                                  // Do While -
        getline(cin,sPlayerInPet);                                                                                        // Input
        transform(sPlayerInPet.begin(), sPlayerInPet.end(), sPlayerInPet.begin(), ::tolower);                             // transform function, uppercase to lower
        if (sPlayerInPet == "cat") {                                                                                      // Set Case If
            iPetChoice = 1;
        }
        else if (sPlayerInPet == "dog") {                                                                                 // Set Case If
            iPetChoice = 2;
        }
        else if (sPlayerInPet == "eagle") {                                                                               // Set Case If
            iPetChoice = 3;
        }
        else {                                                                                                            // If none above then do
            cout << "Ahahah dont be foolin' me! There are no such companions! \nPlease re-validate your companion!\n";
        }
    } while (iPetChoice == 0);
                                                                                             // Do the above while PetChoice equals 0
    cout << "\nNow that we are all set up; to begin the game press Enter.................................. \n\n";
//------------------------------------------------------------------------------------------------------------------------// Finish  //

    NewUser.vSetUserName(sTempUserName);    // Set the username
    NewUser.vSetAge(iTempAge);              // Set the age

    cin.get();

    cout << string( 10, '\n' );

 //--------These are the display Username and Age functions--------//
 //                                                                //
 //   cout << "\nYour Username is: " << NewUser.sGetUserName();    //
 //   cout << "\nYour Age is: " << NewUser.iGetAge();              //
 //   cin.get();                                                   //
 //                                                                //
 //----------------------------------------------------------------//

 //------- Setup Player Starting Location -------//
 //----------------------------------------------//

	NewUser.location = &rooms[0];

 //--------- Setup Player Starting END ----------//
 //----------------------------------------------//

        cout << "Dear " << sTempUserName << ",\n\n"  "The terrible ogres of the north attacked our fair city of Aliaksiam in the early";
        cout << "hours of the morning! Our royals awoke from their slumber to the bloodshed and \ndestruction of the upper castle.\n\n";
        cout << "Cutting a terrible story short, the Kings daughter Anna was kidnapped in the \nheat of battle! \n";
        cout << "The King has requested your assistance in the return of his daughter.\n\nIn need of your help, \nAgatha \n\n";
        cout << "Will you help? : " << endl;

        cout << "\n(Y)es or (N)o?\n" << endl;

        getline(cin,sHelpAnswer);

        cHelpAnswer = sHelpAnswer[0];

        if (cHelpAnswer == 'n')
    {
            cout << "\n\nBye for now, " << sTempUserName << "\nUntil next time!\n\n";
            return 0;
    }
        else if (cHelpAnswer == 'y')
    {
            cout << "\n\nYou immediately make your way to the stables and mount your eligant Horse.\n" << endl;
    }



	while (1)

{

        if (iPlayerLives == 0)
{
        cout << "You stumble over, the last hope to save the princess has been diminished! \nYou return to the Castle of Aliaksium to pass on the bad news to the king." << endl;

        cout << "\nYou scored:\n\n" << iUserPoints << " points.\n" << endl;

        cout << "Better luck next time!" << endl;

        break;
}

        // Display the players location and possible movements.

		cout << "------------------\n" << endl;
		cout << "Location:   " << NewUser.location->name << endl;
		cout << "\nDescription:\n\n" << NewUser.location->description << "\n" << endl;
		if (NewUser.location->north)
			cout << "(N)orth to: " << NewUser.location->north->name << endl;
		if (NewUser.location->south)
			cout << "(S)outh to: " << NewUser.location->south->name << endl;
		if (NewUser.location->east)
			cout << "(E)ast to:  " << NewUser.location->east->name << endl;
		if (NewUser.location->west)
			cout << "(W)est to:  " << NewUser.location->west->name << endl;
		cout << "(Q)uit" << endl;

		// Get input and decide where to go next.

		char input;
        string inputString;

        getline(cin,inputString);	        // Grab everything in the buffer, even if it's more than one character.

        input = inputString[0];	            // Only use the first character, discard the rest.

		if (input == 'q')

//		cout << "Please enter the name of you file in this format:\n\nfirstname_lastname\n\n Thankyou." << endl;
//
//		string iTempFileName;
//
//		getline(cin,iTempFileName);
//
//        ofstream Students(iTempFileName, ios::out);
//        Students << sTempUserName << "\n" << iTempAge << "\n" << iUserPoints;
//
        break;

            cout << quizMaster.poseQuestion().c_str() << endl;
            getline(cin, answer);

		if (quizMaster.isCorrectAnswer(answer))
    {
                	cout << "Thats right" << endl;

                	iUserPoints = iUserPoints + iRightAnswer;


			if (input == 'n' && NewUser.location->north)
				NewUser.location = NewUser.location->north;
			if (input == 's' && NewUser.location->south)
				NewUser.location = NewUser.location->south;
			if (input == 'e' && NewUser.location->east)
				NewUser.location = NewUser.location->east;
			if (input == 'w' && NewUser.location->west)
				NewUser.location = NewUser.location->west;

            if (NewUser.location == &rooms[41])
                {
                cout << "\nAfter many heroic acts, you fend off the horid ogres and return the princess\nhome";

                iUserPoints = (iUserPoints - iWrongAnswer) + iFinishBonus + iLiveBonus;


                cout << "\nYou scored :\n\n" << iUserPoints << " points.\n" << endl;

                cin.get();

                break;
                }

    }

    else
            {

            cout << "\nOh no, you got it wrong! You just lost 10 points and a life.\n\nIf your live reach 0 you must return home\nwithout the princess!\n" << endl;

            iUserPoints = iUserPoints - iWrongAnswer;

            --iPlayerLives;

            cout << "\nYou have " << iPlayerLives << " lives left! Better be careful.\n" << endl;

            cout << "Press Enter to continue\n" << endl;

            cin.get();

            }

}

	delete [] rooms;

    return 0;
}

The revelent part is at the bottom, so I suggest reading bottom upwards.

We don't have classes.h, so we can't compile/link/run this. Anyway, that's a bit too much code to go through. This code doesn't exist anywhere, or at least not in the code that has been posted (unless I missed it):

quizMaster.poseQuestion().c_str()

Somewhere in the code, this array has to get filled in:

RiddleGenerator::QnA RiddleGenerator::mQnA[]

Right now the way it gets filled in is hard-coded:

private:
    struct QnA {
        string question;
        int answer;
    };

    static const int QuestionCount = 2;
    static QnA mQnA[QuestionCount];
    int mAnswer;
};

// THIS IS WHERE YOU INSERT QUESTIONS.
//
// The structure MUST remain the same
//
// { "QUESTION?\n\t1)CHOICE1\n\t2)CHOICE2\n\t3)SO ON", The Number which relates to the ANSWER }

RiddleGenerator::QnA RiddleGenerator::mQnA[RiddleGenerator::QuestionCount] = {
        { "What shape as 4 sides?\n\t1)Triangle\n\t2)Circle\n\t3)Square", 3 },
        { "What is the capital of England?\n\t1)Paris\n\t2)London\n\t3)Washington", 2 }

        // NEW QUESTIONs CAN GO IN THE ABOVE SPACE <---!
};

Right now QuestionCount is a constant variable with value 2. If the number of questions is to be read from the file, you'd have to change it from a constant to a non-constant.

Somewhere there needs to be a function that reads in from the file. I don't know where that function is and whether the specification exists yet. I assume it doesn't since I don't see fstream included in the code anywhere. He needs to write that specification.

If he doesn't know how to use fstream and ifstream, here's a decent tutorial:

http://www.cplusplus.com/doc/tutorial/files/

And there are others out there. Basically at this point, I think a new thread should be started. This one's gotten too long, so people stop looking at it.; The new thread should post all of the relevant code, so it runs, but no more than is necessary for people to get a good understanding of the exact problem that your brother is having. Something that we can run without errors right now that doesn't use external files, but is much shorter. That will require changing his program (obviously keep the original since he's only changing it in order to pinpoint the exact problem).

Basically a fairly short program that runs as is without using an external data file, a paragraph description of how to use the program and what it does, what your brother knows already and what he doesn't, the input file, and a precise question. Best of luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.