0

2 つの関数を使用して出力ファイルにデータを出力する必要があるプロジェクトがあります。1 つの関数はベクトルの値を出力し、もう 1 つの関数は配列の値を出力します。ただし、メインで呼び出される 2 番目の関数は、最初の関数が出力したものを上書きします。最初の関数でファイルを開き、2 番目の関数でファイルを閉じようとしましたが、うまくいきませんでした。どうやら、関数から関数へと移動すると、書き込み位置がファイルの先頭にリセットされます。ただし、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

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 に答える
1

outFile.open("TopicFout.txt", ios_base::app | ios_base::out);だけの代わりに使用outFile.open("TopicFout.txt");

于 2014-11-11T08:24:10.607 に答える