Re: convert string into an array
James Kanze <james.kanze@gmail.com> wrote in message...
/* """
On Jul 3, 10:46 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
I would use a stringstream.
Just curious, but why a stringstream, and not an istringstream?
[...]
std::string str_array = "{201,23,240,56,23,45,34,23}";
std::stringstream Buffer;
Buffer << str_array;
Why those two lines, instead of simply:
std::istringstream Buffer( str_array ) ;
""" */
Aww, c'mon James, we can do better than that. :-}
My original code, revised.
{
std::string stin( "{201,23,240,56,23,45,34,23}" );
std::istringstream in( stin.substr( 1, stin.size()-2 ) ); // <---- :-}
// assumes the strings are always *that* format, "{....}".
// now use this, or Jim's code from here ( with 'Trash' removed! [1]).
std::vector<int> array;
for( std::string line; std::getline( in, line, ',' ); ){
std::istringstream conv( line );
int num(0);
conv >> num;
if( not conv ){ break;}
array.push_back( num );
// conv.clear(); conv.str("");
}
for( std::size_t i(0); i < array.size(); ++i ){
std::cout<< array.at( i ) <<" ";
}
}
// output:201 23 240 56 23 45 34 23
[1]
// > Buffer >> Trash; // Throw away (
char tst = Buffer.peek();
if( tst == '{' || tst == ',' || tst == '}' ){ Buffer.ignore(1); }
--
Bob R
POVrookie