-
reading files
I am reading from a data file sequentially, when i get to the last record in the file it reads it twice and outputs to my output file twice. I am using a while loop with a not end of file condtion, is there a place where i need to add an extra read or something??
-
You may be reading past the end of the file within your loop. It is often easier to test the actual read operation for the end of the file rather than the state of the file. If the read fails then you can quit immeadiately.
Otherwise you're reading the last record, eof isn't being set so the loop continues, and then you're reading again. Only when this next read is carried is eof then set, which means the remainder of you loop will be executed when you've already reached the end of the file.
If this doesn't help, post some code.
-
here is the loop i tried to do an extra read an now it causes an infinite loop
ifstream in("a://visi.txt", ios::in);
ofstream out("c://opreg", ios::out);
if(!in)
{
cout<<"cannot open input file";
return 1;
}
in >> report.accountnum;
in >> report.lastname;
while(!in.eof())
{
in >> report.accountnum;
in >> report.lastname;
out << defaultnum;
out << report.accountnum;
out << "M";
if(strcmp(report.lastname, mchar) <0)
{
out<<fint<<endl;
}
else
{
out<<tint << endl;
}
in>> report.accountnum;
}
-
You don't want an extra read, you just need to test the outcome of an existing read. If you're sure that all records are correctly entered into the file you could do something like -
while(in >> report.accountnum)
{
in >> report.lastname;
//etc
}
instead of
while(!in.eof())
//etc
for the reasons stated in my original post.
-
ok changed my loop to this:
while(in>> report.accountnum)
{
in >> report.accountnum;
in >> report.lastname;
out << defaultnum;
out << report.accountnum;
out << "M";
if(strcmp(report.lastname, mchar) <0)
{
out<<fint<<endl;
}
else
{
out<<tint << endl;
}
}
but now it only does one read, it only grabs the first record
-
You're reading something into report.accountnum twice each loop. Loose the second one, otherwise it'll make your file reading get out of sync resulting in a bad read (where something like a char is extracted when a int is expected) which will cause the stream to fail and force your loop to exit.