On 28 May 2004 11:20:27 -0700 in comp.lang.c++,
measterly@mchsi.com
(Michael Easterly) wrote,[color=blue]
>What is a good way to read a text file and read each line, then assign
>data to variables?[/color]
There is no single answer to that, it depends on many things such as how
complex your data format is, and what kind of error recovery you
require. But,
[color=blue]
> while(!OpenFile.eof())
> {[/color]
that isn't part of it. Don't loop on eof(), instead read until reading
fails. Then check eof() to see if that was the reason, if you still
care.
std::string line;
while(std::getline(openfile, line)
{
[color=blue]
>For example, if I want positions 1-7 to be assigned to a string
>vender, then positions 10-12 to be assigned to a different string how
>is that accomplished?
>
>Here is a sample of the data file:
>
>Y0TH004 210 100 50 5[/color]
OK, your fields appear to be delimited by whitespace. That makes things
easy, since that's the default behavior for stream formatting
operator>>(). You could do something like:
while(std::getline(openfile, line)
{
std::istringstream parse(line);
parse >> f1 >> f2 >> f3 >> f4;
if(parse.good())
// do something with the data.
}
For more complicated input format, one of the first things I think of
these days is the regex library from
http://www.boost.org