Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 261
  • Last Modified:

Reading a file

I need to read in a file that has two numbers seperated by a space on each line
1 2
3 4
5 7
123 254

I need to read these values into a struct. I can't seem to get the correct values into the struct. Any ideas?

struct physical_memory
{
      int log_address;
      int mem_address;
};


class pagemem
{
      private:
            ifstream newfile;
      public:
            pagemem();
            physical_memory *pmem;


};

pagemem::pagemem()
{
      pmem = new physical_memory[255];
      int i =0;

      newfile.open("allocated.dat", ios::in);
      if(newfile.is_open())
      {
            while(!newfile.eof())
            {
                  newfile.ignore(
                  newfile.getline((char*)&pmem, sizeof(pmem));
                  cout << pmem[1].log_address << endl;
            }
      }
}
0
microcoop
Asked:
microcoop
  • 2
1 Solution
 
dennis_georgeCommented:

try this

pagemem::pagemem()
{
     pmem = new physical_memory[255];
     int i =0;

     newfile.open("allocated.dat", ios::in);
     if(newfile.is_open())
     {
          while(!newfile.eof())
          {
                char num[20] ;
                fs >> num ;
                pmem[i].log_address = atoi(num) ;

                fs >> num ;
                arr[i++].mem_address = atoi(num) ;
       }
     }
}
0
 
dennis_georgeCommented:
I would rather suggest you to use vectors instead of using array of structure......
0
 
SirHandoCommented:
You have a text file, read it like a text file.

iostreams handles reading int, float, long etc from the stream, you dont  need to convert it.

Something like this will work

pagemem::pagemem()
{
     newfile.open("allocated.dat", ios::in);
     physical_memory    pm[255];
     int                         i = 0;
     if(newfile.is_open())
     {
          newfile >> ::skipws;
          while( newfile.good() && i<255 )
          {
               newfile >> pm[i].log_address >> pm[i].mem_address;
               //
               // Do what you want with pm[i] now.
               //
               cout << pm[i].log_address << pm[i].mem_address << endl;

               // Next Record
               ++i;
          }
     }
}
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now