2

I am trying to read from a text file properties: char* and int and create objects of class B.Here is my implementation:

 B * p=new B[3];
for(int i=0;i<3;i++)
{
    p[i]=B("John",300);

}
ofstream file("example.txt");

for(int i=0;i<3;i++)
{
    file<<p[i].getName()<<" "<<p[i].GetValue()<<endl;      
}
file.close();
  //saved succesfully

 ifstream file2("example.txt");

B *q=new B[3];
char* temp;
int time1;
for(int i=0;i<3;i++)
{
    file2>>temp>>time1;
    char*name1=new char[strlen(temp)+1];
    strcpy(name1,temp); //here name1 is red correctly
   q[i]=B(name1,time1); // 
}
file2.close();

The saving of the 3 objects is successful ,I have checked the file.However when I am reading from it 3 objects,the first object is correctly created ,but for the other objects the char* propery which I pass gets initialized as "," and the second parameter which is int is also correct.Why does the first object create successfully while the others don't?

1 Answers1

3

file2 >> temp is invalid as temp is an uninitialized pointer. This operator>> needs a preallocated buffer.

I recommend using less 'stars' (zero, ideally) and more standard containers, i.e. std::vector and std::string in this case. That will also solve your memory leaks...

Ok, if you cannot, implement your own functionality-restricted version of std::string. Anything else violates The single responsibility principle and that's not good C++.

If you don't want to go that far, a simple fix is to make temp an actual array with the size of the maximum number of characters you expect the names in the file to be.


Lastly, think about whether you can make B::name char const*, because of this.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74