在两个函数中使用相同的变量

Using same variable in two functions

本文关键字:变量 函数 两个      更新时间:2023-10-16

我有两个函数read()write()。我在read()函数中读取一个文件,并在变量的头中存储一行。现在我希望write()函数将同一行写入新文件。但是我如何使用来自另一个函数的相同变量或信息呢?怎么做呢?

下面是一些关于代码的信息:

在包含必要的文件之后,它说:

HX_INIT_CLASS(HxCluster,HxVertexSet);

类的名称是HxCluster,如果有人能告诉我为什么它不像我们在简单的方式定义类:class class_name {};

I有许多函数,其中两个是read()write()。它们都只有一个参数,即在各自的情况下要读取的文件和要写入的文件。我不知道在这里写代码是否会有帮助。

如果我没理解错的话,这就是c++中结构/类/对象的作用。例如:

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);

注意,上面的代码是无效的。这只是一个样本。你必须修复所有的错别字,缺少名称空间,标题,添加流打开/关闭/错误处理等。

从read返回变量并将其作为参数传递给write。像这样

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

在函数之间传递信息是一项需要学习的c++基本技能。

如果我理解对了,那么我建议你将变量的信息保存为字符串或整型,这取决于它是什么类型的信息。

我还建议总是包含一些代码,以便我们能够给你更多的帮助

您可以让写取一个参数,void write(std::string text),或者您可以将您读取的字符串存储为全局变量std::string text在您的。cpp文件的顶部,text = ...在您的读取函数(替换…使用ifstream或任何你使用的),然后写text在你的写函数

当然,使用指针!

void main(){
  char* line = malloc(100*sizeof(char));
  read_function (line);
  write_function (line);
}
void read_function(char* line){
  .... read a line
  strcpy (line, the_line_you_read_from_file);
}
void write_function (char* line){
  fprintf (fp,"%s", line);
}