ifstream overflow in while loop
May 30, 2014 at 7:52am UTC
Hi Guys,
Im stuck on how to break out of this loop when it hits eof(it out puts the last line twice). all the research ive done says to use a break statement however we are not allowed to do that in this class. any help would be greatly appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct student{
char name[128];
int mark;
};
void insertionSortStrings(student array[100], int length);
int main ()
{
int size = sizeof (student);
ifstream ins;
ins.open("marks.txt" );
student record[100];
if (!ins.good())
{
cout << "Error reading file." << endl;
return 0;
}
else
{
int i = 0;
while (!ins.eof());
{
ins >> record[i].name;
ins >> record[i].mark;
i++;
}
insertionSortStrings(record, i);
for (int j=0; j<i; j++)
{
cout << record[j].name << "\t" << record[j].mark << endl;
}
}
return 0;
}
void insertionSortStrings(student array[], int length)
{
for (int i = 1; i < length; i++)
{
for (int k = i; k > 0 && array[k].mark > array[k-1].mark; k--)
{
student temp;
temp = array[k];
array[k] = array[k-1];
array[k-1] = temp;
}
}
}
May 30, 2014 at 8:16am UTC
you have a ';' closing your while btw, you sure it's reaching the end?
May 30, 2014 at 8:19am UTC
I'd use something like:
while (getline(ins,string my_string))
thats the only way I know to stop the while before the last loop you are getting. I suppose you can use C++ features.
May 30, 2014 at 8:39am UTC
The best would be:
1 2 3 4 5
int i = 0;
while (ins >> record[i].name >> record[i].mark) // Note: no ;
{
i++;
}
But you can also do this
1 2 3 4 5 6 7 8
int i = 0;
while (!ins.eof()) // Note: no ;
{
ins >> record[i].name;
ins >> record[i].mark;
if (!ins.eof())
i++;
}
May 30, 2014 at 10:28am UTC
oh i didnt see that ;
that was from when i was messing about with other ideas. thanks guys they worked perfectly :)
Topic archived. No new replies allowed.