Use vectors if you want to and there are many reasons why that is the best way to proceed. But before abandoning arrays altogether there is a very simple way to allocate enough space in the array and that is to read the file and count how many records there are. This means the file is read twice - no major problem.
(Adding and deleting records can be handled in a similar way without writing special array sizing functions that vectors have inbuilt.)
5a8Ym39o6 thank you again. How can I cout the elements of the vector to make sure that the values are stored in the objects? Also, is there is a way to make the loop stop until the end of the text instead of using 5?
Kemort thank you for your input. I guess a vector will serve my purpose more than an array because its size will be dependent on the elements I include in the text file.
Kemort thank you for your input. I guess a vector will serve my purpose more than an array because its size will be dependent on the elements I include in the text file.
Angel, I won't belabor the point beyond this comment but make sure you are clear that the number of elements in the text file here will invariably determine the size of the container whatever choice is made. There is no magic involved.
Why are all the class member variables public? Normally the member variables should be private and then you would use member functions to access these private variables. In this instance you could use a constructor with the proper arguments to properly initialize the member variables, or you could use a temporary instance of your class and use your current functions to modify the member variables before inserting the temporary instance into the vector.
I tried to run the code but I received three errors. The first one on this line void print() const { cout << ID << " " << Type << " " << feeder_pt << " " << axle_pt << endl;}
#include <string>
#include <fstream>
#include <vector>
usingnamespace std;
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
class trucks {
public :
int ID;
string Type;
double feeder_pt;
double axle_pt;
public:
void setID (int id) {ID = id;}
void setType (string type) {Type = type;}
void setfeeder (double feeder) {feeder_pt = feeder;}
void setaxle (double axle) {axle_pt = axle;}
};
int main ()
{
ifstream myfile("sequence.txt");
int ID;
string Type;
double feeder_pt;
double axle_pt;
vector<trucks> truck;
for(int i = 0; i < 5; i++)
if(myfile >> ID >> Type >> feeder_pt >> axle_pt)
{
truck.push_back(trucks());
}
}
I guess it should be working, however, I cannot guarantee until I access the elements of the vector to make sure. This is what I don't know how to do..
Truck no 1: 984763 A 20.000000 18.000000
Truck no 2: 762613 A 19.000000 17.000000
Truck no 3: 587123 A 22.000000 16.000000
Truck no 4: 897654 D 85.000000 19.000000
Program ended with exit code: 0