0

The problem was

"create an array of at leat four pointers to Reader object. Use the New operator to create at leat four pointers to derived class objects and assign them to the array"

The reader is the base class. The fantasyReader, horrorReader, misteryReader, and scienceReader are derived class.

I have to read from Reader.txt

"""""""""""contents""""""""""""
David
0   <-Mystery category
John
1   <-Horror category
Mark
2   <-Science category
Sarah
3   <-fantasyReader
"""""""""""""""end"""""""""""""""""""

What I have

enum {HORROR, MYSTERY, SICENCE, FANTASY}; 

int main(void)
{
    Reader *obj[10];

    ifstream reader_file;

    int category =0; 
    string name; 
    string number; 
    int counter = 0;
    if(reader_file.is_open())
    {

        while( getline(reader_file, name, '\n') && 
                getline(reader_file, number, '\n'))
        { 
            switch(category)
            {
                case FANTASY:
                    obj[counter++] = new fantasyReader(name);
                    break;
                case MYSTERY: 
                    obj[counter++] = new mysteryReader(name);
                    break
                case HORROR:
                    obj[counter++] = new horrorReader(name);
                    break;
                case SCIENCE:
                    obj[counter++] = new scienceReader(name);
                    break;
            }
        }
    }
}

Im not sure if my codes are answering the question above.

6
  • Please remove all HTML tags from your question. To format the code, select it in the editor and hit the {} button. Commented May 29, 2011 at 10:03
  • Do you experience any problems when trying out the code? Commented May 29, 2011 at 10:06
  • Oh Thank you!! I didn't know;; Commented May 29, 2011 at 10:12
  • @newb: there was a missing ; in your code (after counter = 0). Commented May 29, 2011 at 10:13
  • Looks fine to me though I haven't tested it. You just have to open the file (using reader_file.open() first) :D Commented May 29, 2011 at 10:16

1 Answer 1

2

Your problem is that you read string data (chars) but the enumeration values correspond to integers. Try:

category = atoi (number.c_str());

switch(category) {
      ...
}

Also, don't forget to open and close the file:

reader_file.open ("readers.txt", ifstream::in);
...
reader_file.close();
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, atoi(). number is char*, atoi converts char* to int. Or one can just use boost:lexical_cast ;)
Nasibov: No. number is declared as string, presumably the one inside namespace std. This is not char*.

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.