Re: input formatted file
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?
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
}
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34