reading txt file into class and inputting into a vector

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kylie991
    New Member
    • Feb 2009
    • 41

    reading txt file into class and inputting into a vector

    Hi everyone. I am just starting out on my assignment on classes. We havent long learnt about them so I am struggling a little on how to do the following.

    Below is a small part of the definition of the class.. I have not provided all of it as I dont have questions on the rest of it.... I was wondering how I am supposed to open a txt file in the class constructor target....

    Code:
    class target
    {
       // Definition for class target
       // Class target contains the internal logic for the game of target
       // (user interaction is outside the class in application program)
       //
     public:
       target();
        // default constructor  
        // Opens small default dictionary ("dict.txt") and reads words into 
        // vector wordList
        // Default dictionary contains only lower case words of length 4-9
        // Sets centreLetter and otherLetters to spaces.
    So far I have tried and failed. I know I have it wrong but I was hoping someone could point me in the right direction :-)

    I will definately be asking my tutor for help this week in class but I would really like to make a start on it!

    Code:
    target :: target()
        // default constructor  
        // Opens small default dictionary ("dict.txt") and reads words into 
        // vector wordList
        // Default dictionary contains only lower case words of length 4-9
        // Sets centreLetter and otherLetters to spaces.
        {
           ifstream infile;
           string fname;
           int data;
           infile.open(fname.c_str()); 
           if (infile.fail()) 
           { 
             cout << "File not found " << endl; 
          return EXIT_FAILURE; 
          }      
          infile >> data;
        }
    Thx in advance
    K.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    First, your class description says that the default constructor opens a default dictionary "dict.txt" so I don't uinderstand why your constructor isn't doing that. Shouldn't it just open "dict.txt" ?

    What you are doing is opening a file using a name contained in a local string object but you have failed to put a file name in that object.

    Comment

    • kylie991
      New Member
      • Feb 2009
      • 41

      #3
      when I make it the file name.. eg.
      target :: target()
      // default constructor
      // Opens small default dictionary ("dict.txt") and reads words into
      // vector wordList
      // Default dictionary contains only lower case words of length 4-9
      // Sets centreLetter and otherLetters to spaces.
      {
      ifstream infile;
      string fname;
      int data;
      infile.open(fna me."dict.txt") ;
      if (infile.fail())
      {
      cout << "File not found " << endl;
      return EXIT_FAILURE;
      }
      infile >> data;
      centreLetter = ' ';
      otherLetters = ' ';
      }
      it comes up with errors saying "aggregate 'std::ifstream infile' has incomplete type and cannot be defined..
      expected unqualified -id before string constant
      returning a value from a constructor
      [Build Error] [target.o] Error 1

      I am just stuck on what I am doing wrong...

      Comment

      • newb16
        Contributor
        • Jul 2008
        • 687

        #4
        1) - read doc on ifstream, note what headers you should include in order to use it ( fstream )
        2) As you already noticed, the compiler probably pointed you to this line - fname."dict.txt " . This is not a valid expression.
        3) return EXIT_FAILURE; . Yes, constructors don't return value. You can thrown an exception if something went wrong.

        Comment

        • kylie991
          New Member
          • Feb 2009
          • 41

          #5
          THank you :-) I didnt even think of that.. I got the first part to work .. or so it seems. it is at least compiling now... I really really appreciate it!!

          Comment

          • kylie991
            New Member
            • Feb 2009
            • 41

            #6
            Okay I just realised I am still doing it wrong. I need to obviously open dict.txt which I am now doing but it is reading into int data. I need it to read words into vector wordList.... how would I do that??? I have tried changing the part that says string data to vector<string> wordList but it doesnt like what I am doing?? any ideas? :-)

            target :: target()
            // default constructor
            // Opens small default dictionary ("dict.txt") and reads words into
            // vector wordList
            // Default dictionary contains only lower case words of length 4-9
            // Sets centreLetter and otherLetters to spaces.
            {
            ifstream infile;
            string fname;
            string data;
            infile.open("di ct.txt");
            if (infile.fail())
            {
            cout << "File not found " << endl;
            }
            infile >> data;
            centreLetter = ' ';
            otherLetters = ' ';
            }

            Comment

            • weaknessforcats
              Recognized Expert Expert
              • Mar 2007
              • 9214

              #7
              What is the format of your disc file? Are your words separated by spaces or by non-spaces, like a comma?

              When you infile>>Astring , you get one word since the >> operator stops on whitespace. I would assume you could push_back to your vector right then. If the disc file uses comma separators, the you will need to use getline() so you can specify a comma delimiter. Here you use a char buffer with getline() and on the next line you assign the buffer to a string and then push_back the string to your vector.

              Comment

              • kylie991
                New Member
                • Feb 2009
                • 41

                #8
                You guys are all so helpful :) But me being me keeps confusing myself. I know it is probably such a simple thing to do...

                I did a test doing the following

                for (int i = 0; i <= 100;i++)
                {
                infile >> data;
                cout << data << endl;
                }

                cout << "this is data outside the loop " << data;

                When it does this it seems to output each string up to 100 in the loop which is what I would expect it to do and if I just ask it to output data outside the loop it outputs the last string. That makes sense...

                But as soon as I add the vector wordList when I run it the executable opens and closes so quickly I dont know what I am doing wrong...

                for (int i = 0; i <= wordList.size() ; i++) // I have made it <= as the vector size is 0 and the loop will not run if I say if int i < vector size will it??
                {
                infile >> wordList.at(i);
                wordList.push_b ack(i);
                cout << wordList.at(i) << endl;
                }

                Am I still off track or almost there??? I know it is probably something sooo simple.. but I just dont understand why it isnt working as a vector...

                Comment

                • kylie991
                  New Member
                  • Feb 2009
                  • 41

                  #9
                  ok I worked it out.. although it is a little manual :) so dont worry about answering the previous question... YAY I did something on my own :)

                  Comment

                  • kylie991
                    New Member
                    • Feb 2009
                    • 41

                    #10
                    ok my next question is about calling a function into the test.cpp file... for some reason a different function is not working. Am I calling it wrong?????

                    I

                    int main()
                    {
                    string fname;
                    cout << "\t Welcome to Target Helper \n\n";
                    target t; // create a new target object
                    char choice = ' ';

                    while (choice != 'Q')
                    {
                    printMenu();
                    cin >> choice;
                    // convert choice to to uppercase
                    choice = toupper(choice) ;
                    // ... !
                    switch (choice)
                    {
                    case('N') : t.newGame();
                    //break;
                    ............... ............... ............... ......


                    My class function (implementation file) is very basic.. I just want to get it working before I add the algorithms.

                    So I have just done as below... it seems the problem is coming from the main.cpp file though.......??

                    void target::newGame (char centre, string others)
                    // pre : none
                    // post : set centre letter and other letters for a new game of target
                    {
                    cout << "Enter centre letter : ";
                    }

                    the error message showing is
                    no matching function for call to 'target::newGam e()'
                    candidates are: void target::newGame (char, std::string)
                    [build error][puzzle.o] Error 1

                    Comment

                    • kylie991
                      New Member
                      • Feb 2009
                      • 41

                      #11
                      ooh I worked it out :-)

                      Comment

                      • weaknessforcats
                        Recognized Expert Expert
                        • Mar 2007
                        • 9214

                        #12
                        Originally posted by kylie991
                        ok I worked it out.. although it is a little manual :) so dont worry about answering the previous question... YAY I did something on my own :)
                        You aren't by any chance using Visual Studio.NET? I mean you mention the thing opening and closing so fast you couldn't read the output.

                        If so, Visual Studio.NET has two kinds of builds: Debug (the default) and Release.

                        The Debug build .exe has code in it to support the debugger. When you Start the program, Visual Studio sees it is a debug .exe and ASSUMES you are using your debugger and that you have already installed the necessary breakpoints to halt the code. If you are not using the debugger all you see is a black flash as your program goes in and out of execution.

                        Instead of Start, if you select Start Without Debugging, you are telling Visual Studio that while this is a debug .exe you are not using your debugger. In thie case, Visual Studio will halt execution at the end of main() with "Press any to continue...".

                        That is, you don' need to add code at the end fo main() to halt the program.

                        Comment

                        • kylie991
                          New Member
                          • Feb 2009
                          • 41

                          #13
                          No I'm using bloodshed dev c++. I got everything I was asking sorted out. although I kind of made it manual by getting it to read in the exact number of words in the file.. I was stuck on how to change it.....

                          Anyway now I'm onto the harder stuff... but I dont think I will work on it today. I will probably have a few questions where I am stuck but I want to see if I can do it on my own :-)

                          Comment

                          • kylie991
                            New Member
                            • Feb 2009
                            • 41

                            #14
                            okay so now I am trying to work out in my assignment on how to output each character in a string... I understand what I am doing wrong in this but I am not sure how to make it right??

                            string c;

                            for (int i = 0; i < wordList.size() ; i++)
                            {
                            c = wordList.at(i);
                            for (int j = 0; j < c.length(); j++)
                            {
                            int sum = 0;
                            char k;
                            sum = sum + c.length();
                            k = c.at(j);
                            if (k == centreLetter) //why is this comparison resulting in my program crashing?
                            {
                            cout << c << endl;
                            }
                            }
                            }

                            Comment

                            • kylie991
                              New Member
                              • Feb 2009
                              • 41

                              #15
                              ok dont worry about the previous thread. I managed towork it out... it has taken me a while.. but I am getting there and it is helping me to understand it all..

                              Now I am stuck on a merge sort.. I think I might give myself a break for the night after I post this as I have been working on it for hours.........

                              okay so I have sorted each character vector into ascending order and now I need to merge them. well sort of..

                              I have two vectors.. one that contains the letters the user enters (lets call it userlist) (there are 9 in total) and then another vector which contains the "dict.txt" list.

                              Basically I need to check the dict vector against the userlist vector. If all the characters in userlist vector are used up then I need to output the string.
                              Does that make sense? Would I use a merge sort for that?????? I dont know if I need to??

                              anyway here is the mergesort code I have been working on but it seems to be crashing so im not 100% sure what I am doing wrong

                              vector <char> result;
                              int left = 0 ; // index for c
                              int right = 0 ; // index for otherletters
                              while ( left < c.size() && right < otherLetters.si ze())
                              {
                              if (c.at(left) < otherLetters.at (right))
                              {
                              result.push_bac k(c.at(left));
                              left++;
                              }
                              else
                              {
                              result.push_bac k(otherLetters. at(right));
                              right++;
                              }
                              for (int i = left ; i < c.size();i++) // i think the error is here somewhere...?
                              result.push_bac k(c.at(i));
                              for (int i = right ; i < otherLetters.si ze(); i++)
                              result.push_bac k(otherLetters. at(i));

                              }
                              for (int i = 0; i < result.size(); i++)
                              {
                              cout << result.at(i);
                              }
                              cout << endl;
                              }

                              thanking you all again for your help :) it really has helped me work through my assignments. especially when it is hard to get help from my classes.

                              Comment

                              Working...