Read data from a file into array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • macus
    New Member
    • Jul 2007
    • 5

    Read data from a file into array

    Dear All,

    I have 2 cvs file like this:

    <spec.csv>
    Type,sybType,ID
    CASH,ON,1
    FRA,1x4,2
    ...

    <data.csv>
    ID,Rate
    1,3
    2,5.23
    ...

    I want to read the files and put them into a 2D array. I am new to c++, pls help to give me some simple code to do this.

    The follow are some of my current code to read one csv file, but still not success.

    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    #include <string>
    
    #define DELIM ","
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        ifstream specf, dataf;
        int      specId[50],dataId[50];
        char     *buff,*sep;
        char     *InstrumentType[50],*subType[50];
        int      i=0,j=0;
        
        
        specf.open(argv[1]); //Open Spec File
        if (specf.is_open()) 
        {
            while(specf.getline(buff,256))
            {
                sep = strtok(buff, DELIM);
                while (sep != NULL)
                {
                      if(i==0) 
                      {
                         InstrumentType[j]=sep;
                         cout<<j<<"IT="<<InstrumentType[j]<<endl;
                         i++;
                      }
                      else if(i==1)
                      {
                         subType[j]=sep;
                         cout<<j<<"ST="<<subType[j]<<endl;
                         i++;
                         
                      }
                      else if(i==2)
                      {
                         specId[j]=atoi(sep);
                         cout<<j<<"ID="<<specId[j]<<endl;                     
                         i=0;
                      }
                      sep = strtok(NULL, DELIM);          
                }
                j++;            
            }
        
        }
        else
        {
            cout <<"Error opening file "<<argv[1]<<"\n";
            return -1;
        }
        
        for(j=0;j<10;j++)
        {
            cout<<j<<":IT="<<InstrumentType[j]<<":ST="<<subType[j]<<":ID="<<specId[j]<<endl;
        }
        
    }
    Thanks.
  • ravenspoint
    New Member
    • Jul 2007
    • 111

    #2
    A problem that I notice is that you are defining pointers to characters, but you are NOT initializing where those pointers point.

    For example

    char *buf

    getline(buff,25 6)

    will write the data from file to a random location - who knows where?

    Better is:

    char buf[258]

    getline(buff,25 6)

    which will write your data to somewhere that the compiler has laid aside for the purpose.

    Some of you oither character pointers have the same problem.

    James

    Comment

    • macus
      New Member
      • Jul 2007
      • 5

      #3
      What I need to correct if I want to use a pointer to access the array !?It is because I don't want to limit the size of the array.Thanks.

      Originally posted by ravenspoint
      A problem that I notice is that you are defining pointers to characters, but you are NOT initializing where those pointers point.

      For example

      char *buf

      getline(buff,25 6)

      will write the data from file to a random location - who knows where?

      Better is:

      char buf[258]

      getline(buff,25 6)

      which will write your data to somewhere that the compiler has laid aside for the purpose.

      Some of you oither character pointers have the same problem.

      James

      Comment

      • ravenspoint
        New Member
        • Jul 2007
        • 111

        #4
        Arrays, by definition, have a limited size.

        In this case, it is no big deal. Notice that 256 in your call to getline? You will never get more than 256 characters returned from that routine.

        James

        Comment

        • macus
          New Member
          • Jul 2007
          • 5

          #5
          It is a big problem, because every lines won't exceed 256 characters. But, the program will read every line data and put into the array. Since the date many be so long, I don't want to array to limit the size of the data storage array. How do I use it with pointers ?Thanks.

          Comment

          • Rasputin
            New Member
            • Jun 2007
            • 33

            #6
            I suggest the use of vectors over arrays. use push_back() method to fill them.

            Ras.

            Comment

            • macus
              New Member
              • Jul 2007
              • 5

              #7
              Could you mind to give me some example code!? I don't know how to use the vector.Thanks.

              Originally posted by Rasputin
              I suggest the use of vectors over arrays. use push_back() method to fill them.

              Ras.

              Comment

              • Rasputin
                New Member
                • Jun 2007
                • 33

                #8
                Originally posted by macus
                Could you mind to give me some example code!? I don't know how to use the vector.Thanks.
                [code=c]
                std::ifstream file; //declare an input stream
                vector<string> vData; // declare your vector as a container for strings
                string temp; //needed to push the data in the vector

                try{
                file.open (path); // replace "path" by your path, or declare and define the variable path
                }
                catch(...){
                //Do something
                }

                while(!file.eof ()){ // Read the file to a vector until its end.
                file>> temp; //put in temporary string
                vData.push_back (temp); //fill the vector
                }

                //Close your file after

                [/code]

                This code has not been tested for errors but the idea is here. You should very easily find all the methods of vectors on google. And don't forget to include the library vector.h


                Ras.
                Last edited by Rasputin; Jul 20 '07, 06:38 AM. Reason: comments added

                Comment

                • ravenspoint
                  New Member
                  • Jul 2007
                  • 111

                  #9
                  Originally posted by Rasputin
                  And don't forget to include the library vector.h


                  Ras.
                  Umm. Excuse me, but shouldn't that be

                  Code:
                  #include <vector>
                  He will also need to write

                  Code:
                  #include <string>
                  using namespace std;
                  There is quite a learning curve on STL vector use. It seems a bit cruel to tell someone to use them, and then just point them to google.

                  STL vector<string> is definitely the correct way to go, but the OP needs a gentle tutorial.

                  Comment

                  • Rasputin
                    New Member
                    • Jun 2007
                    • 33

                    #10
                    Originally posted by ravenspoint
                    There is quite a learning curve on STL vector use. It seems a bit cruel to tell someone to use them, and then just point them to google.
                    Your comment makes sense, and I do take some blame.
                    But it seemed to me that a page like http://www.cplusplus.com/reference/stl/vector/ , on top results in google for simple queries, would be a more concise and helpful information than going on from scratch in this one thread. Also, a simple search on vectors in this forum would pop up all the basics. I admit, this way is not the most courteous.

                    As for the includes, it maybe was clumsy to assume one would automatically think to include "string" and I should have remembered that "vector.h" used in Borland is not universal.

                    Oh, "using namespace std;" is not needed.

                    Kindly,


                    Ras.
                    Last edited by Rasputin; Jul 20 '07, 06:18 PM. Reason: misquote

                    Comment

                    • ravenspoint
                      New Member
                      • Jul 2007
                      • 111

                      #11
                      I bet this comes up all the time. ( I have only being posting here for one day, so I am just finding my way around. ) My thought is that this site should have a few pointers to frequently used gentle tutorials ( not reference guides!!!!! ) that we could use. Because you are perfectly correct, it would be wasteful to fill up every thread with every persons lame attempt to provide a finely tuned tutorial.

                      Well, if you leave out "using namespace std;" then you are going to have to add std:: in front of every reference to vector - which I had noticed you did not do in the code you posted.

                      Comment

                      • Rasputin
                        New Member
                        • Jun 2007
                        • 33

                        #12
                        Originally posted by ravenspoint
                        Well, if you leave out "using namespace std;" then you are going to have to add std:: in front of every reference to vector - which I had noticed you did not do in the code you posted.
                        I understand the whole thing now: I use Borland SDK, and instead of doing "#include <vector>", I work with "#include "vector.h" and then the vectors I use are not actually the ones of the standard library... no "using namespace std;" needed, and last 2 posts confusions understood.

                        And actually as I'm writing this I only understand now why I was having an unexpected behaviour doing certain specific manipulations with vectors (see one of my previous threads).... that was worth the discussion!

                        Actually, I'm really wondering if any of the info pointed here has helped the initial poster...


                        Ras.

                        Comment

                        • ravenspoint
                          New Member
                          • Jul 2007
                          • 111

                          #13
                          Originally posted by Rasputin

                          Actually, I'm really wondering if any of the info pointed here has helped the initial poster...


                          Ras.
                          The OP has been very quiet. We may have scared them away ;-(

                          If you are still there, macus, then post and let us know how you are getting along with your problem - and we will try to refocus this thread.

                          Let us know what C++ toolset you are using. MSVC, Borland or something else.

                          Comment

                          Working...