C++ 尝试使用2个函数写入一个文件

C++ 尝试使用2个函数写入一个文件,c++,arrays,file,writefile,C++,Arrays,File,Writefile,我有一个项目,需要我使用两个函数在输出文件中打印数据。一个函数打印向量的值,另一个函数打印数组的值。但是,main中调用的第二个函数将覆盖第一个函数打印的内容。我试着在第一个函数中打开文件,在第二个函数中关闭文件,但没有成功。显然,当您从一个函数移动到另一个函数时,写入位置将重置为文件的开头。但是,我无法使用seekp();因为我们没有在课堂上讨论过。关于我应该怎么做有什么见解吗 void writeToFile(vector<int> vec, int count, int ave

我有一个项目,需要我使用两个函数在输出文件中打印数据。一个函数打印向量的值,另一个函数打印数组的值。但是,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();
}
void writeToFile(向量向量、整数计数、整数平均)
{
出流孔的直径;
outFile.open(“TopicFout.txt”);
//将向量的所有值打印到TopicFout.txt中

outFile使用
outFile.open(“TopicFout.txt”,ios_base::app | ios_base::out)
而不仅仅是
outFile.open(“TopicFout.txt”);

正如罗杰在评论中建议的那样,您可以使用引用指针将流的
传递给函数

最简单的方法应该是通过引用传递它。通过这种方式,您可以在主函数上声明并初始化流的

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;

}
void writeToFile(流和输出文件、向量向量向量、整数计数、整数平均值)
{
//将向量的所有值打印到TopicFout.txt中

outFile在两个函数之外打开和关闭文件,并将指向流的
的指针或引用传递给每个函数。避免在第二个函数中使用未初始化的变量
outFile
。按照Roger Rowland所写,在函数之外控制打开和关闭。
ios_base::out
是超流。
流的
将不管怎么说,我都不能用这个,因为这不是我们在提问时讨论过的话题。
void writeToFile(std::ofstream outFile, vector<int> vec, int count, int average) {...}