I have following structure.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
struct station {
std::string id;
std::string code;
std::string station_name;
station(std::vector<std::string> &in) : id(in[0]), code(in[1]),
station_name(in[2]) {}
station(): id (""), code (""), station_name(""){}
bool operator<( const station& rhs ) const {
return this->station_name < rhs.station_name;
}
};
int main(int argc, char **argv) {
std::ifstream ifs(argv[1]);
if ( ifs.peek() == EOF ) {
exit ( 1 );
}
// Read the input file and update the database
std::string line;
station prev, current;
std::set<station> my_set;
while( ifs.good()&& std::getline(ifs,line) ) {
std::stringstream lineStream(line);
std::string token;
std::vector<std::string> input;
while(std::getline(lineStream,token,',')) {
input.push_back(token);
}
station st(input);
my_set.insert(st);
}
}
I am reading a file which has information related to railway stations in the following format
ID,Station Code,Station Name
I am reading this file line by line and creating a object of station and then pushing the same into the std::set<station>
It gets crashed after some time, around after reading 21448 line. I have around 403523 lines
What is the problem here.
This program works properly on Linux but not on windows
I get debug assertion failed
The constructor that takes an array worries my.
Edit
Based on the updated question:
The problem is the constructor that takes a vector.
You are accessing the elements without check if they exist.
So if any line of input is bad (ie not all values are present) then the vector will not be as big as required and result in undefined behavior.
If you change these lines:
Into:
Then called the station constructor with these parameters (as would have been nice in OO code). Then you would not have seen the crash. Some error checking would also be nice.
Note:
There is no need to check good() here. If the stream is not in a good state then getline() will do nothing. The conversion of the stream (the return value of getline()) to a bool is also checking if the state is the stream is valid for further reading and if not will convert to false (eventually).
Original
try this: