C++ 打印到文件 Bug:报告每个时间步错误?

C++ Print to file Bug: Reporting each time step error?

我正在尝试将我的 C++ 程序结果存储到文本文件,但我只存储了最后一个命令。请任何人帮助我。我能够在文本文件上获得输出,但不是每次执行的整个步骤结果。

int main()
{

    //File write name setting from the fstream dirrectory
    fstream file;
    file.open("Pressure.txt", ios::out);


    double length;
    double Dx;
    double Pl;
    double pr;
    double px;
    double NumberOfGrids;

    std::cout << "Enter the length of Slab: ";
    std::cin >> length;

    std::cout << "\nEnter the grid size: ";
    std::cin >> Dx;

    NumberOfGrids = length / Dx;
    std::cout << "\nTotal number of grids: " << NumberOfGrids << "\t";

    std::cout << "\nEnter the Pressure at length (L): ";
    std::cin >> Pl;

    std::cout << "\nEnter the Reservoir Pressure: ";
    std::cin >> pr;  

    do
    {
        px = Pl + ((pr - Pl)* (0.5*(Dx*NumberOfGrids / length)));
        --NumberOfGrids;
        std::cout << px << "\t\t";
        file << "Pressure along the Core Length " << endl << px << "\t\t";
        file.close();
    } while (NumberOfGrids >= 0);

您的问题是,您在循环内关闭了文件。所以第一次迭代会很好,之后 file 将不再是打开的文件,因此无效。

你应该这样做:

do
{
    px = Pl + ((pr - Pl)* (0.5*(Dx*NumberOfGrids / length)));
    --NumberOfGrids;
    std::cout << px << "\t\t";
    file << "Pressure along the Core Length " << endl << px << "\t\t";
    // Do not close file here!
} while (NumberOfGrids >= 0);
file.close(); // close it here instead!

那么你的代码应该运行没问题。