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
|
#include <iostream>
#include <string>
#include <vector>
#include <regex>
std::vector<int> extract_integers_from( const std::string& str )
{
// an optional + or - sign followed by a sequence of one or more decimal digits
static const std::regex int_re( "[+\\-]?\\d+" ) ;
static const std::sregex_iterator end ;
std::vector<int> numbers ;
// http://en.cppreference.com/w/cpp/regex/regex_iterator
for( std::sregex_iterator iter( str.begin(), str.end(), int_re ) ; iter != end ; ++iter )
numbers.push_back( std::stoi( iter->str() ) ) ; // convert the matched character to int
return numbers ;
}
std::vector< std::vector<int> > make_2d_array( const std::string& str )
{
std::vector< std::vector<int> > array_2d ;
std::size_t max_row_sz = 0 ;
std::istringstream stm(str) ;
std::string line ;
while( std::getline( stm, line ) ) // for each line in the string
{
auto row = extract_integers_from(line) ;
if( max_row_sz < row.size() ) max_row_sz = row.size() ;
array_2d.push_back( std::move(row) ) ;
}
for( auto& row : array_2d ) row.resize(max_row_sz) ; // make all rows of the same size
return array_2d ;
}
int main()
{
const std::string str = "1,2,3,4,5,\n"
"6,7,8,9,0,\n"
"1,2,3,4,5\n"
"6,7,8,9,0,\n"
"6,-7,8\n" // added for testing
"\n" // added for testing
"begin:6a7 (8)-9end!\n" ; // added for testing
const auto array_2d = make_2d_array(str) ;
for( const auto& row : array_2d )
{
for( int v : row ) std::cout << std::showpos << v << ' ' ;
std::cout << '\n' ;
}
}
|