How to use fstream (in particular, stream) through function parameters

Hi, I am starting with c++ and this is one of my assignments and I am a bit stuck. This is not all my code, this is just a fragment of what I need help with. I am trying to make one function designed to export everything with this function to a text file called result.txt. Therefore, the line "this work" should be displayed when opening the file, but when I run the file, I get errors, for example

"Error C2065: 'out': undeclared identifier"

"Error C2275: 'std :: ofstream': illegal use of this type as an expression"

"IntelliSense: type name not resolved"

"IntelliSense: identifier" out "is undefined"

 #include <iostream> #include <string> #include <fstream> using namespace std; //prototypes void output(ofstream& out); int main() { output(ofstream& out); ifstream in; in.open("inven.txt"); ofstream out; out.open("results.txt"); return 0; } void output(ofstream& out) { out << "does this work?" << endl; } 

Now it’s very late, and I’m just hiding what I’m doing wrong.

+3
source share
2 answers

First of all, this is normal:

 void output(ofstream& out) { out << "does this work?" << endl; } 

However, it is not:

 int main() { output(ofstream& out); // what is out? ifstream in; in.open("inven.txt"); ofstream out; out.open("results.txt"); return 0; } 

This is the first error you get: "Error C2065:" out ": uneclared identifier" because the compiler does not yet know about it.

In the second snippet, you want to output the output using a specific ostream& . Instead of calling a function, you are declaring a function that is not valid in this context. You should call it with the given ostream& :

 int main() { ifstream in; in.open("inven.txt"); ofstream out; out.open("results.txt"); output(out); // note the missing ostream& return 0; } 

In this case, you call output with the out parameter.

+6
source

Since you described yourself as a beginner, I will answer accordingly and, I hope, in an educational manner. Here's what happens: think of fstream , ofstream and ifstream as types of smart variables (even if you know which classes, think about it for the sake of logical clarity ). Like any other variable, you must declare it before using it . After it is declared, this variable can hold a compatible value . The fstream variable types are intended for storing files . All its variants have the same thing, only what they do is different.

You use a variable to open a file , use in your program, and then close .

Hope this helps

+1
source

All Articles