detraveller
detraveller

Reputation: 295

Using same variable in two functions

I have two functions read() and write(). I read a file in the read() function and store a line in the header in a variable. Now i want the write() function to write that same line to a new file. But how can i use the same variable or information from the other function? What is the way to do this?

Here is some info about the code:

After including necessary files, it says this

HX_INIT_CLASS(HxCluster,HxVertexSet);

The name of the class is HxCluster and it would be great if someone can tell me why it is not like we define classes in the simple way: class class_name {};

The I have many functions out of which two are read() and write(). They both take one argument only which is the file to be read and the file to be written to in the respective cases. I don't know if writing the code for that will help here.

Upvotes: 0

Views: 2227

Answers (4)

quetzalcoatl
quetzalcoatl

Reputation: 33566

If I understood you well, this is just what in C++ the structures/classes/objects are for. For example:

class FileLineWriter
{
public:
    FileLineWriter();

    void read(istream& inputfile);
    void write(ostream& putfile);

private:
    string line_of_text;
};

void FileLineWriter::read(istream& s)
{
    // s >> this->line_of_text; // possible, but probably will not do what you think
    getline(s, this->line_of_text);
}

void FileLineWriter::read(ostream& s)
{
    s << this->line_of_text;
}

...
FileLineWriter writer;
writer.read(firstfile);
writer.write(secondfile);

note that the above is NOT a working code. It is just a sample. You will have to fix all typos, missing namespaces, headers, add stream opening/closing/error handling, etc.

Upvotes: 5

mwerschy
mwerschy

Reputation: 1708

You can either make write take an argument, void write(std::string text) or you can store the string you read as a global variable std::string text at the top of your .cpp file, text = ... in your read function (replace ... with ifstream or whatever you use) and then write text in your write funcion.

Upvotes: 0

Thomja
Thomja

Reputation: 257

If I have understood this right then I would suggest that you save the info on the variable to a string or an int depending on what kind of info it is.

I would also recommend to always include some code for us to be able to give you some more help

Upvotes: 0

john
john

Reputation: 8027

You return the variable from read and pass it as a parameter to write. Something like this

std::string read()
{
   std::string header = ...
   return header;
}

void write(std::string header)
{
   ...
}

std::string header = read();
write(header);

Passing information between functions is a basic C++ skill to learn.

Upvotes: 1

Related Questions