everyone! I am new for C++ and now work on a C++ project.The whole structure has been completed.But I have been wondering about
how to build the vector of different objects and how to read the file since the beginning.
In my problem, first I have to read a txt file with readObstacles(std::istream &fs) that has the following format:
RECTANGLE 1 2.5 2 2 0.2
CIRCLE 1 2.5 1.2
RECTANGLE 4 2 2 2 0.3
(each obstacle begins a new line)
I need to read the data information of different obstacles and store these obstacles in a vector.
Class Obstacle is the base class with two sub-classes CIRCLE and RECTANGLE.
I try to put the these different obstacles (that i think should have their data info) in a obstacle vector and then call the virtual function they both have.
Below is the code I try to do with:
vector<Obstacle> obsdata;
Myworld::readObstacles(std::istream &fs)
{
std::string shape;
double num1,num2,num3,num4,num5;
while(fs>>shape>>num1>>num2>>num3>>num4>>num5)
{
if(shape=="CIRCLE") {
CIRCLE c;
c.m_Xc=num1;
c.m_Yc=num2;
c.m_Radius=num3;
obsdata.push_back(c);
}
if(shape=="RECTANGLE") {
RECTANGLE r;
r.center_x=num1;
r.center_y=num2;
r.width=num3;
r.height=num4;
r.angle=num5;
obsdata.push_back(r);
}
}
}
MyWorld::writeMatlabDisplayCode(std::ostream &fs)
{
for( i = 0; i < obsdata.size(); i++ )
obsdata[i].writeMatlabDisplayCode(fs);
}
I know it doesn’t work but i don’t know what i should do.
Any words will help. Thanks !
You could try just reading the whole line at a time then tokenize the values…
I would delete this vector of pointers in your MyWorld destructor: