1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
#include <iostream>
#include <string>
#include <map>
#include <regex>
#include <vector>
#include <sstream>
class patient
{
public:
explicit patient( int id = 0, int requestTime = 0, int appointTime = 0, int waitingTime = 0,
double latitude = 0, double longitude = 0 )
: id(id), requestTime(requestTime), appointTime(appointTime),
waitingTime(waitingTime), latitude(latitude), longitude(longitude) {}
std::string to_csv() const
{
using std::to_string ;
return "id=" + to_string(id) + ", requestTime=" + to_string(requestTime) +
", appointTime=" + to_string(appointTime) + ", waitingTime=" + to_string(waitingTime) +
", latitude=" + to_string(latitude) + ", longitude=" + to_string(longitude) ;
}
explicit patient( std::string csv ) : patient()
{
// regular expression to match name = value
static const std::regex re( "(\\w+)\\s*=\\s*(\\S+)\\s*(?:$|,)" ) ;
static const std::sregex_iterator end ;
for( std::sregex_iterator iter( csv.begin(), csv.end(), re ) ; iter != end ; ++iter )
{
const auto& match = *iter ;
// convert values from string to numbers : may throw
if( match[1] == "id" ) id = std::stoi( match[2] ) ;
else if( match[1] == "requestTime" ) requestTime = std::stoi( match[2] ) ;
else if( match[1] == "appointTime" ) appointTime = std::stoi( match[2] ) ;
else if( match[1] == "waitingTime" ) waitingTime = std::stoi( match[2] ) ;
else if( match[1] == "latitude" ) latitude = std::stod( match[2] ) ;
else if( match[1] == "longitude" ) longitude = std::stoi( match[2] ) ;
}
}
private:
int id;
int requestTime;
int appointTime;
int waitingTime;
double latitude;
double longitude;
};
std::vector<patient> get_patients( std::istream& csv_stream )
{
std::vector<patient> result ;
try
{
std::string csv ;
while( std::getline( csv_stream, csv ) ) result.push_back( patient(csv) ) ;
}
catch( const std::bad_alloc& ) { throw ; } // allocation failure: re-throw
catch( const std::exception& ) // bad input: put the stream into a failed state
{
csv_stream.clear( csv_stream.failbit ) ;
}
return result ;
}
std::ostream& put_patients( const std::vector<patient>& patients, std::ostream& csv_stream )
{
for( const patient& p : patients ) csv_stream << p.to_csv() << '\n' ;
return csv_stream ;
}
int main() // minimal test driver
{
std::istringstream csv_file
(
"id=1,requestTime = 2, appointTime = 3, waitingTime = 4, latitude=5.6, longitude=7.8\n"
"requestTime = 12, waitingTime = 14, id=11,latitude=15.6, longitude=17.8,appointTime = 13 \n"
"id=21, longitude=27.8,requestTime = 22, waitingTime = 24,,latitude=25.6 \n"
"requestTime = 32, id=31\n"
);
const auto patients = get_patients(csv_file) ;
put_patients( patients, std::cout ) ;
}
|