I am having trouble with the title above. I have tried开发者_C百科 the following but it does not act in the correct behaviour.
void ArrayIntStorage::read(ifstream& in)
{
if(in.is_open())
{
while(!in.eof())
{
in.getline(arrayStorage, sizeof(in));
}
}
}
ofstream& ArrayIntStorage::write(ofstream &out) const
{
for (int i = 0; i < sizeof arrayStorage; i++)
{
out << arrayStorage[i] << endl;
}
return out;
}
I am a novice at C++ programming, so I am probably doing something stupid. Thanks in advance.
I am going to guess that you are reading/writing an array of integers. It appears that you might be incorrectly reading the sizeof(in), rather than the sizeof(arrayStorage) in your read method.
There are several problems with your code. For starters, you
don't show us the declaration of arrayStorage
, so we have to
guess it: I'll guess int arrayStorage[N]
, (where N
is some
constant). Following that, for reading:
- It's never correct to use `istream::eof` in a loop. This function only has meaning once input has failed; before that, it can return `false` when there is nothing else to read, and `true` even though the last input succeeded. The function you're interested in is `fail`, which is what is called indirectly whenever the `istream` is used in a context which requires a `bool`.
- `getline` requires a `char[]`, and reads characters, not int's.
If all the file contains is these int's, the standard idiom for reading them would be:
for (int i = 0; in && i < N; ++ i) {
in >> arrayStorage[i];
}
In practice, you'll probably want a bit more: is it an error if the file doesn't contain enough int's? if it contains too many? And you'll want to verify after the failure that the failure was due to end of file, and not some random gibberish in the file. Or maybe you want (or need) to validate the format more, ensuring that there is never more than one int in a line.
Your output function looks almost OK; the last index should be N
, and not sizeof arrayStorage
(which returns the number of bytes in the array, not the number of elements). Later, downstream,
you'll want to check that there has been no errors after
closing the file; there's nothing more frustrating than
a program which says it's succeeded, when in fact only part of
the data made it to disk.
精彩评论