Search code examples
c++variable-assignmentfstreamifstreamofstream

ofstream creates a file but doesn't write


Here's the code, I try to look up solutions but the things I've tried haven't worked. Also, the if statement at the bottom of the main that checks if the file is opened, fails and says it cannot open the file, but I don't know what to do with that error.

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int row = 6;
const int col = 8;
void cellTemp (double check[][col], double);
int main()
{
    ifstream in;
    string input;
    ofstream out;
    string output;
    double grid[row][col];
    double t1, t2, t3, t4, tol;

    cout << "Enter input file name: \n";
    cin >> input;
    cout << "Enter output file name: \n";
    cin >> output;

    in.open(input.c_str());
    out.open(output.c_str());

    in >> t1 >> t2 >> t3 >> t4 >> tol;


    for(int i = 0; i < 6; i++)
    {
        for(int c = 0; c < 8; c++)
        {
            grid[i][c] = 0;
        }
    }

    //  Initializes top and bottom rows to 0
    for(int i = 0; i < 8; i++)
    {
        grid[0][i] = t1;
        grid[7][i] = t3;
    }
    //  Initializes left and right columns to 0
    for(int i = 1; i < 5; i++)
    {
        grid[i][0] = t4;
        grid[i][7] = t2;
    }

    cellTemp(grid, tol);
    if(out.is_open())
    {
        for(int i = 0; i < 6; i++)
        {
            for(int c = 0; c < 8; c++)
            {
                out << grid[i][c];
            }
            out << endl;
        }
        out.flush();
    }
    else
    {
        cout << "Cannot open file. \n";
    }
    out.close();
    in.close();
}
void cellTemp (double check[][col], double tolerance){

    double copy[row][col];
    double max = 0;
    double prev = 0;
    double prevMax;
    double prevTol = tolerance;

    tolerance = -1;
    while(prevMax > tolerance)
    {
        tolerance = prevTol;
        //  Copies the array before performing actions
        for(int i = 0; i < 6; i++)
        {
            for(int c = 0; c < 8; c++)
            {
                copy[i][c] = check[i][c];
            }
        }

        //  Sets cell values
        for(int i = 1; i < 5; i++)
        {
            for(int c = 1; c < 7; c++)
            {
                check[i][c] = (check[i-1][c] + check[i+1][c] +
                        check[i][c-1] + check[i][c+1]) / 4;
            }
        }

        for(int i = 1; i < 5; i++)
        {
            for(int c = 1; c < 7; c++)
            {
                prev = check[i][c] - copy[i][c];
                if(prev > max)
                {
                    max = prev;
                }
            }
        }
        prevMax = max;
        max = 0;
    }
}

Solution

  • grid[7][i] = t3;
    

    you dont have [7] rows mate think you want grid[5][i] = t3; ?