Re: input formatted file
"James Kanze" <james.kanze@gmail.com> wrote in message
news:fb7ae73a-a05f-45b3-bd54-421528186843@j20g2000hsi.googlegroups.com...
On Nov 24, 5:37 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
"Jun" <junh...@gmail.com> wrote in message
news:81126096-6872-439f-9bbc-0ebd631536a2@y5g2000hsf.googlegroups.com...
I've a data file
========
4 1 1 1 1
5 1 1 1 1 1
2 1 1
========
first column represents the how many values in this line, and then
followed by values. I've seen some codes using
*******************************
ifstream inf
while(inf >> data1 >> data2)
*******************************
to read data, just very beautiful and simple code, could anyone give
me some advices for my case? thank you in advance.
One thing I would do is use std::getline( inf, somestring );
then put it into a stringstream.
Why a stringstream, and not an istringstream? You don't want to
write to it?
----------
I don't use streams that often other than stringstream where I do tend to do
both input and output and the full blown stringstream is required. I'm not
100% sure of the advantages of using istringstream over stringstream though,
other than maybe some overhead costs.
std::stringstream Data( somestring );
At this point you can check if the number of values are correct.
int Count;
if ( Data >> Count )
{
int Value;
int ValueCount;
while ( Data >> Value )
{
ValueCount++;
// dosomething with Value
}
if ( ValueCount != Count )
{
// throw error here. Number at beginning does not match
// number of values.
}
}
Even easier:
std::istringstream s( line ) ;
size_t count ;
s >> count ;
std::vector< int > data((std::istream_iterator< int >( s )),
(std::istream_iterator< int >()) ) ;
if ( ! s ) {
// Some input error...
} else if ( data.size() != count ) {
// syntax error
}