Afficher un message
Vieux 07/04/2008, 23h59   #3
Jerry Coffin
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: how to avoid ifstream::get() when EOF is coming

In article <ZPoKj.2704$xd5.2319@newsfe17.phx>, drmario@cox.net says...
> I'm using VC++ 8.0 Express Edition on Windows XP Home Edition. I've
> opened a file with ifstream:pen(). The text in the file will have the
> general format of:
>
> michael jordan 90
> roger moore 79
> your name 100
>
> So basically a first name, last name, grade, \n. I'm using
> ifstream::get() to one by one read each char of the first and last name into
> a cstring (no not string data type. An array of chars. I suppose
> technically an array of pointers to chars). Then I use ifstream >> to read
> the grade. It's kinda a long story why, but this is the (inefficient, I
> know) way I've chosen to do it and I'm not going to change it.


So your question is: "How do I do this correctly while insisting on
doing it completely incorrectly?"

If you're not using a string, you probably want to use an array of char,
but almost certainly NOT an array of pointers to char. You're starting
with a poor idea, but that would be far worse still.

> Taking James Kanze's previous advice I inserted a buncha statements to
> check the stream's error state flags after every input. I discovered that
> after I read the last student's grade using ifstream >>, the program sets my
> stream's eofbit to true. This of course makes sense.


No, it does NOT! After reading the last data in the file, eofbit should
NOT be set yet. You should see eofbit set ONLY when you try to read
something and the final data in the file had _previously_ been read.

If you insist on reading the names into arrays of char (why?) you could
take a look at ifstream::getline to do the job. Since you're reading
structured data, I'd advise reading the data into a structure:

struct person {
const int len = 20;
char first_name[len];
char last_name[len];
int grade;
};

std::ifstream &operator>>(std::ifstream &in, person &p) {
in.getline(first_name, len, ' ');
in.getline(last_name, len, ' ');
in >> grade;
return in;
}

Then reading a file full of data in that format into a vector (for
example) looks something like:

std::vector<person> people;

std::copy(std::istream_iterator<person>(input),
std::istream_iterator<person>(),
std::back_inserter(people));

--
Later,
Jerry.

The universe is a figment of its own imagination.
  Réponse avec citation
 
Page generated in 0,06104 seconds with 9 queries