printing a function more than once

#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

string name(string fname, ifstream& in)
{
while (!in.eof())
{
in >> fname;
}
return fname;
}

int main()
{
string fname;
ifstream in;
in.open("in.txt");
ofstream out;
out.open("out.txt");


cout << name(fname, in) << endl;
cout << name(fname, in) << endl; //this part is completely ignored, can't get it to print again. what am i doing wrong. thank you in advance



system("PAUSE");
return 0;
}
//this part is completely ignored, can't get it to print again. what am i doing
It is not ignored. The function is called but the stream in is at the end and therefore name return an empty string.

1
2
3
4
5
6
7
8
string name(string fname, ifstream& in)
{
while (!in.eof())
{
in >> fname;
}
return fname;
}


This reads all the name in the file but return only the last one at the end.
Do not loop on !eof(). This does not work the way you expect. eof is set true only after you make a read attempt on the file (line 5). This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the entire cin operation as the condition in the while statement.

@OP - PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

Topic archived. No new replies allowed.