【问题标题】:Trying to write in one file using 2 functions尝试使用 2 个函数写入一个文件
【发布时间】:2014-11-11 07:21:34
【问题描述】:

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

【问题讨论】:

  • 在这两个函数之外打开和关闭文件,并为每个函数传递一个指向ofstream的指针或引用。
  • 避免在第二个函数中使用未初始化的变量outFile。如 Roger Rowland 所写,控制函数外部的打开关闭。

标签: c++ arrays file writefile


【解决方案1】:

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

【讨论】:

  • ios_base::out 是多余的。 ofstream 无论如何都会添加它
  • 无论如何我都无法使用它,因为它不是我们在提出问题时涉及的主题。
【解决方案2】:

正如 Roger 在 cmets 上建议的那样,您可以使用引用指针将 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类没有这样的定义。

【讨论】:

    猜你喜欢
    • 2011-02-14
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2021-02-13
    相关资源
    最近更新 更多