Re: Reading an array from file?
On Aug 4, 10:00 pm, Jerry Coffin <jerryvcof...@yahoo.com> wrote:
In article <4a784940$0$303$14726...@news.sunsite.dk>, f...@gk.com
says...
Hi I have a .txt file containing:
[-0.00231844, -0.02326, 0.0484723, 0.0782189, 0.0917853,
[ ... ]
I still need to "tokenize" this string into its double
parts. Before throwing myself into cumbersome code I would
like to hear if anyone has a good idea to do this the right
way.
I'm not sure if it's really "right" (some would argue that
it's downright wrong), but for your purposes, the commas are
essentially the same as white space -- i.e. they're something
between the data that you ignore. As such, I'd probably just
create a locale where ',' is treated as white space, and then
let the iostream handle the "parsing" involved:
Where commas and opening and closing braces are white space.
But a lot depends on how much error checking is deamed
necessary. In his case, a priori, commas aren't "just white
space", since something like "1.2,,3.4" should probably produce
an error, and if the file doesn't start with a '[' and end with
an ']', it's also an error.
There are several ways of tackling this; Victor's loop, but
checking the value of dummy_char, is probably the simplest for a
beginner to write and understand. If error checking on the
input format is not desired (although it generally isn't a good
idea to drop such error checking), the easiest solution is
probably a FloatWithSeparator class, something like:
class FloatWithSeparator
{
public:
operator double() const
{
return myValue ;
}
friend std::istream& operator>>(
std::istream& source,
FloatWithSeparator& dest )
{
char separator ;
source >> separator >> myValue ;
return source ;
}
private:
double myValue ;
} ;
You can then define the vector with something like:
std::vector< double > v(
(std::istream_iterator< FloatWithSeparator >( file )),
(std::istream_iterator< FloatWithSeparator >()) ) ;
--
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