So basically, I got a file with the following content in it:
4 //Number of stations
Spadina;76 156 //Name, number of student passes, and number of adult passes
Bathurst;121 291
Keele;70 61
Bay;158 158
i got an object that takes 3 paramaters, the name of the station for example spadina, the number of studnet passes so 76, and number of adult passes so 156. how can i read the file and set it ?
std::vector<Station> stations;
if(std::ifstream in {"stations.txt"}) //open the file
{
std::size_t number_of_stations;
if(in >> number_of_stations) //read the number of stations
{
std::string name;
std::size_t students, adults;
for(std::size_t i = 0; //split onto multiple lines for readability
(i < number_of_stations) && //make sure we don't read too much
std::getline(in, name, ';') && //read the name
(in >> students >> adults) && //read the number of passes
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore the rest of the line
++i)
{
stations.push_back(Station(name, students, adults)); //add the station
}
}
else
{
std::cerr << "Couldn't read number of stations" << std::cerr;
}
}
else
{
std::cerr << "Couldn't open stations.txt" << std::endl;
}
You can also make use of static integer data member and increase it as you go on pushing (creating) objects in vector. This would help you determine how many objects you've created.
@HabibAurangabad: there are multiple issues with your code:
- usingnamespace std; is bad practice (Google will tell you why)
- You neglect to check if the file could be opened successfully
- You hard-code your program to break if a line is linger than 80 characters
- You do all sorts of unnecessary substring math
- You separate declaration from initialization on lines 76 and 77
It is good that you are trying to be helpful, but please be aware of the mistakes you are making. Often the person you are trying to help does not know any better and will learn your mistakes as the right way to do things.