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

时间:2015-09-15 16:28:18

标签: c++ visual-c++

我正在尝试将我的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);

1 个答案:

答案 0 :(得分:1)

您的问题是,您关闭循环内的文件。所以第一次迭代会很好,之后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!

然后你的代码运行正常。