Re: convert string into an array
"James Kanze" <james.kanze@gmail.com> wrote in message
news:1183536448.703333.102290@n60g2000hse.googlegroups.com...
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?
I don't know. I use stringstream for all types of conversion and it works.
What real advantage would istringstream give me?
[...]
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 ) ;
Becuase I normally use stringstring in one of my templates:
template<typename T, typename F > T StrmConvert( const F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}
If I change this to
std::string temp( from );
then I get compiler warnings at times depending on F.
warning C4244: 'argument' : conversion from 'const float' to
'std::_Iosb<_Dummy>::openmode', possible loss of data
and I go for 0% warnings in my code. I know that the form I use doesn't
give any warnings.
char Trash;
Buffer >> Trash; // Throw away (
Throw away, or verify, as a syntax check? (In my experience,
you can never verify input too much.)
Agreed, but in most instances where I'm using stringstream for conversion
I've verified the data before I try to convert it, or the output makes it
obvious there was a problem. With user input data I would definately do
syntax checking of the string before/during/after the conversion.
int Value;
std::vector<int> Data;
while ( Buffer >> Value )
while ( Buffer >> Value && Trash != '}' )
This is really not needed though, unless there is extraneous data after
the ) such as
{201,23,240,56,23,45,34,23}75
etc... (not going to comment on the rest)
And
if ( Trash != (Data.empty() ? '{' : ',') ) {
Buffer.setstate( std::ios::failbit ) ;
}
here.
Data.push_back( Value );
Buffer >> Trash; // Throw away , or )
}
And a final error check:
if ( ! (Buffer >> std::ws && Buffer.get() == EOF ) {
error ...
}
// Display vector data
for ( std::vector<int>::iterator it = Data.begin(); it !=
Data.end();
++it )
std::cout << *it << " ";
}
(But I like your basic algorithm better than the one I
suggested.)