#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
struct cluster_t // contents of one line in the file
{
double first = 0.0 ; // omit the in-class member initializer in legacy C++
double second = 0.0 ;
std::vector<int> rest ;
};
// replace ',' '[' or ']' with space
std::string clean( std::string line )
{
for( char& c : line ) // C++11 range-base for loop; rewrite in legacy C++
if( c == ',' || c == '[' || c == ']' ) c = ' ' ;
return line ;
}
// extract the cluster_t in a line (minimal validation)
bool extract_from( const std::string& line, cluster_t& result )
{
std::istringstream stm( clean(line) ) ; // use a string stream for the extraction
if( stm >> result.first >> result.second ) // if we can read the first two numbers
{
// read the rest into the vector
int v ;
while( stm >> v ) result.rest.push_back(v) ;
return stm.eof() ; // true if we have read everything up to the end of line
}
returnfalse ; // badly formed line
}
std::vector<cluster_t> from_file( const std::string& file_name = "surf_db.txt" )
{
std::vector<cluster_t> result ;
std::ifstream file(file_name) ; // file_name.c_str() in legacy C++
std::string line ;
while( std::getline( file, line ) )
{
cluster_t cluster ;
if( extract_from( line, cluster ) ) result.push_back(cluster) ;
}
return result ;
}
int main() // minimal test driver
{
constchar* const test_file_name = "surf_db_test.txt" ;
constchar* const test_data = "192.65 28.9043 [255, 255, 0, 0, 64, 224, -111]\n""166 31 [176, 251, 255, 25, 243, 3, 0, 128, 999]\n""badly formed line\n""1234 5678\n" // also badly formed
"123.4 56.789 [ 55, 0, 0, 0, 64, 224, -333, bad. ]\n""123.4 56.789 [ 55, 0, 0, 0, 64, 224, -333, 255 ]\n";
std::cout << test_data << "---------------------------\n" ;
// create a test file
std::ofstream(test_file_name) << test_data ;
// test the code
std::vector<cluster_t> clusters_read = from_file(test_file_name) ;
for( constauto& cluster : clusters_read )
{
std::cout << "{ " << cluster.first << ", " << cluster.second << ", [ " ;
for( int v : cluster.rest ) std::cout << v << ' ' ;
std::cout << "] }\n" ;
}
}