Actually I didn't understand what you were trying to do with the input statements, where both the
roll_num
and
name
are read from the file twice, first at line at line 21, then again at line 27.
I re-wrote that part of the code to just use
fin >>
for each of the six items, and didn't bother with
getline()
at all. If you do want to use getline with space as a delimiter, remember that there is a space after the
roll_num
, which will be considered the end of the string. That means the contents of
name
will be an empty string. To fix that, you need to skip the leading whitespace.
Either do this (no getline)
1 2
|
fin >> data[index].roll_num;
fin >> data[index].name;
|
or this:
1 2
|
fin >> data[index].roll_num >> ws;
fin.getline(data[index].name, 20, ' ');
|
Also, if you wanted to specify the length in the first case, you could do
|
fin >> setw(20) >> data[index].name;
|
And I couldn't understand what kind of a check this is if(fin) index++; . Can you please explain this? I've never seen such a check before. |
Most newcomers are aware of the end-of-file flag. In fact there are four flags associated with the file stream, good, bad, fail and eof. In general use, the most useful of these is fail. You could test it like this:
See
http://www.cplusplus.com/reference/ios/ios/fail/
Because it is so commonly used, there is a convenient shorter syntax,
if (fin)
or the opposite condition,
if (!fin)
, thus it is a convenient way to check that all is ok, nothing has failed.
if (fin)
gives the same result as
if (!fin.fail())
.
See
http://www.cplusplus.com/reference/ios/ios/operator_bool/
Hope that helps.
By the way, line 48
for(int i=0; i<size; i++)
is still looping a fixed number of times, rather than the actual number of items which were read from the file. You should use
index
rather than
size
here.