在两个函数中使用相同的变量
Using same variable in two functions
我有两个函数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);
}
相关文章:
- 是否可以将变量/函数返回作为模板参数传递
- 是否有一种方法可以修复编译器未找到特定的OPENCV变量/函数
- 访问实例化类的变量/函数
- 如何在变量函数参数列表中检测给定类型的参数的可用性,并在处理完所有参数后采取行动
- C 多组变量函数参数
- 最有cpu效率的方法是使用std::算法和变量函数模板的参数
- 在此作用域中未声明条件变量函数
- C 关于将数组复制到向量并调用其变量 /函数
- 仅在C 中的一个变量上,两个变量函数的数值集成(使用数值配方库)
- 在应用变量函数的矩阵元素上循环
- 如何向调试器隐藏变量/函数名
- C++11变量函数类型模板参数
- 变量函数参数的奇怪问题
- C++变量函数和cout
- c++模板变量函数未定义引用
- 我可以使用枚举类值作为变量函数的参数吗?
- 从另一个类访问变量/函数
- <"变量/函数"的多重定义>
- 从c++到C文件中定义的变量/函数的未定义引用
- 为什么转换变量函数参数很重要?