我有一个项目要求我使用两个函数在输出文件中打印数据。一个函数打印矢量的值,另一个函数打印数组的值。但是,在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();
}
答案 0 :(得分:1)
使用outFile.open("TopicFout.txt", ios_base::app | ios_base::out);
代替outFile.open("TopicFout.txt");
答案 1 :(得分:1)
正如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 一致的编译器,那么传递ofstream也应该没问题:
void writeToFile(std::ofstream outFile, vector<int> vec, int count, int average) {...}
否则将调用复制构造函数,但是对于ofstream类没有这样的定义。