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;
}
It has already read through the whole file the first time you called name so when it's called the second time there is nothing more to read.

If you want to print the name twice why don't you just store the name in a variable and print the variable twice?

1
2
3
string nam = name(fname, in);
cout << nam << endl;
cout << nam << endl;

And you probably should name your function something more desciptive, something that describes what it is doing (like readName). name is a good name for a variable but not for a function.
Last edited on
@Peter87 ughh thank you so much haha. So simple but I couldn't figure it out. thank you
Topic archived. No new replies allowed.