尝试使用两个函数写入一个文件
Trying to write in one file using 2 functions
我有一个项目,要求我使用两个函数在输出文件中打印数据。一个函数打印矢量的值,另一个打印数组的值。但是,在main中调用的第二个函数会覆盖打印的第一个函数。我试过在第一个函数中打开文件,在第二个函数中关闭它,但没有成功。显然,当您从一个函数移动到另一个函数时,写入位置会重置为文件的开头。但是,我无法使用seekp();因为我们在课堂上还没有真正涉及到这一点。对我该怎么做有什么见解吗?
void writeToFile(vector<int> vec, int count, int average)
{
ofstream outFile;
outFile.open("TopicFout.txt");
// Prints all values of the vector into TopicFout.txt
outFile << "The values read are:" << endl;
for (int number = 0; number < count; number++)
outFile << vec[number] << " ";
outFile << endl << endl << "Average of values is " << average;
}
void writeToFile(int arr[], int count, int median, int mode, int countMode)
{
ofstream outFile;
// Prints all values of the array into TopicFout.txt
outFile << "The sorted result is:" << endl;
for (int number = 0; number < count; number++)
outFile << arr[number] << " ";
outFile << endl << endl << "The median of values is " << median << endl << endl;
outFile << "The mode of values is " << mode << " which occurs " << countMode << " times." << endl << endl;
outFile.close();
}
使用outFile.open("TopicFout.txt", ios_base::app | ios_base::out);
而不是仅使用outFile.open("TopicFout.txt");
正如Roger在评论中建议的那样,您可以通过引用使用的指针将ofstream
传递给函数。
最简单的方法应该是通过引用传递它。通过这种方式,您可以在主函数上声明并初始化ofstream
ofstream outFile; // declare the ofstream
outFile.open("TopicFout.txt"); // initialize
... // error checking
... // function calls
outFile.close(); // close file
... // error checking
你的第一个功能可能看起来像:
void writeToFile(ofstream& outFile, vector<int> vec, int count, int average)
{
// Prints all values of the vector into TopicFout.txt
outFile << "The values read are:" << endl;
for (int number = 0; number < count; number++)
outFile << vec[number] << " ";
outFile << endl << endl << "Average of values is " << average;
}
如果您使用的是符合C++11的编译器,那么也可以像这样传递流:
void writeToFile(std::ofstream outFile, vector<int> vec, int count, int average) {...}
否则,复制构造函数将被调用,但对于ofstream类并没有这样的定义。
相关文章:
- 挂起和取消挂起一个文件DLL
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何将class.cpp和class.hpp编译为一个.o文件
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 如何从整个磁盘中排除要装载的一个文件
- 如何将模板和非模板函数放在一个文件中
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 使用 scope 运算符 (::) 引用另一个文件中的类
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- c++ 提升如果 .extension() == " "这意味着这个文件是一个文件夹?
- 是否可以在 c++ 中创建一个文件并为其提供属性以将其隐藏?(在 Ubuntu 上)
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?