file writing within function
I want to be able to write to a file with a function with a file object that i opened up in the main function. I have put a little half pseudo-code and half real code in the following box. For spacing reasons related to writing it into a csv file, I cannot open the file within the functions (I know how to do it, it just does not serve me purpose. Thanks for your help in advance
Code:
call function x (string);
int main()
{
collect file name information
ifstream myfile (writefile.c_str());
if (myfile.is_open())
{
get string info
call function x with string
}
else cout << "error opening file" << endl;
}
void function x (string)
{
myfile << string;
}
It's weird how I can use the myfile << string; in the place where I call the function, but I cannot do it with the function. How do I get the functionality in there? Like I said, I can't open the file in the function, I just need the FUNCTIONALITY in the function. And when I compile it the only error I get is one saying "mywrite undeclared (first use in this function)"
Re: file writing within function
Code:
call function x (ifstream &, string &);
int main()
{
collect file name information
ifstream myfile (writefile.c_str());
if (myfile.is_open())
{
string s;
get string info( s );
x( myfile, s );
}
else cout << "error opening file" << endl;
}
void function x (ifstream &f, string &s)
{
f >> s;
}
Take care to avoid using types as variable names, even in pseudo code.
The trick is to accept these by reference, not value (so they're not copied).
Also, input streams send data TO variables, not the other way around (direction of the >>, not <<)
Re: file writing within function
I cannot quite get the syntax to word, I initialized the function with
void function(string line, ifstream &handle);
and called it with
function(line, &myfilehandle);
and it is still not working
Re: file writing within function
Not quite
try
void function(string &line, ifstream &handle);
and call it with
function(line, myfilehandle);
Also, the variable name myfilehandle is misleading. The reason is that ifstream isn't a file handle, it's an object that represents an open file. A handle is a rather specific OS interface concept, not a stream object.
Minor point though.
The point above is that string & is required such that changes made in the function are visible to the caller.
Similarly, when you pass parameters by reference, you need not provide the address of it, just the variable itself.