尝试使用两个函数写入一个文件

Trying to write in one file using 2 functions

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

我有一个项目,要求我使用两个函数在输出文件中打印数据。一个函数打印矢量的值,另一个打印数组的值。但是,在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类并没有这样的定义。

相关文章: