0

我有一个项目需要我使用两个函数在输出文件中打印数据。一个函数打印向量的值,另一个函数打印数组的值。但是,在 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();
}
4

2 回答 2

1

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

于 2014-11-11T08:24:10.607 回答
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 类没有这样的定义。

于 2014-11-11T08:43:51.753 回答