How to read 4x4 2D-array from file

I am doing Branch and Bound.I want to read 4x4 integers from file
How do I do this,here is what i tried but it seems wrong with my output



My txt file is:
82 83 69 92
77 37 49 92
11 69 5 86
8 9 98 23

If necessary this is the whole code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
#define N 4

struct Node
{
    Node* parent;
    int pathCost;
    int cost;
    int workerID;
    int jobID;
    bool assigned[N];
};

Node* newNode(int x, int y, bool assigned[],
              Node* parent)
{
    Node* node = new Node;

    for (int j = 0; j < N; j++)
        node->assigned[j] = assigned[j];
    node->assigned[y] = true;

    node->parent = parent;
    node->workerID = x;
    node->jobID = y;

    return node;
}

int calculateCost(int costMatrix[N][N], int x,
                  int y, bool assigned[])
{
    int cost = 0;

    bool available[N] = {true};

    for (int i = x + 1; i < N; i++)
    {
        int min = INT_MAX, minIndex = -1;

        for (int j = 0; j < N; j++)
        {
            if (!assigned[j] && available[j] &&
                costMatrix[i][j] < min)
            {
                minIndex = j;

                min = costMatrix[i][j];
            }
        }

        cost += min;

        available[minIndex] = false;
    }

    return cost;
}

struct comp
{
    bool operator()(const Node* lhs,
                   const Node* rhs) const
    {
        return lhs->cost > rhs->cost;
    }
};

void printAssignments(Node *min)
{
    if(min->parent==NULL)
        return;

    printAssignments(min->parent);
    cout << "Assign Worker " << char(min->workerID + 'A')
         << " to Job " << min->jobID << endl;

}

int findMinCost(int costMatrix[N][N])
{
    priority_queue<Node*, std::vector<Node*>, comp> pq;

    bool assigned[N] = {false};
    Node* root = newNode(-1, -1, assigned, NULL);
    root->pathCost = root->cost = 0;
    root->workerID = -1;

    pq.push(root);

    while (!pq.empty())
    {
      Node* min = pq.top();

      pq.pop();

      int i = min->workerID + 1;

      if (i == N)
      {
          printAssignments(min);
          return min->cost;
      }

      for (int j = 0; j < N; j++)
      {
        if (!min->assigned[j])
        {
          Node* child = newNode(i, j, min->assigned, min);

          child->pathCost = min->pathCost + costMatrix[i][j];

          child->cost = child->pathCost +
            calculateCost(costMatrix, i, j, child->assigned);

          pq.push(child);
        }
      }
    }
}


int main()
{
    ifstream myfile;
    string file;
    int costMatrix[N][N];
    int i, j, row, col;

    cout << "Please enter a file name(data.txt): ";
    cin >> file;

    myfile.open(file.c_str());
    if(!myfile)
    {
         cout << "File does not exist." << endl;
    }

    myfile >> row >> col;

    for(i = 0; i < row; i++)
    {
        for(j = 0; j < col; j++ )
        {
            myfile >> costMatrix[i][j];
            cout << costMatrix[i][j] << ' ' << endl;
        }
         cout << '\n'; // newline
    }


    myfile.close();
  
    cout << "\nOptimal Cost is "
        << findMinCost(costMatrix);

    return 0;
}


Thank you everyone in advance!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    const int N = 4;
    ifstream myfile;
    string file;
    int costMatrix[N][N];
    
    cout << "Please enter a file name: ";
    cin >> file;
    
    myfile.open(file.c_str());
    if(!myfile)
    {
        cout << "File does not exist." << endl;
    }
    
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++ )
        {
            myfile >> costMatrix[j][i];
            cout << costMatrix[j][i] << ' ';
        }
        cout << '\n';
    }

    myfile.close();
    
    return 0;
}


Please enter a file name: text.txt
82 83 69 92 
77 37 49 92 
11 69 5 86 
8 9 98 23 
Program ended with exit code: 0
Thank you @againtry it works now!
Last edited on
Why my array cannot be taken and it seems does not work in the function

Retardation?
Hello lychee,

Looking at the second code that you posted.

The first question I have is what IDE/compiler are you using? And what C++ standard are you compiling to?

For now take everything from line 7 to line 123 and put a comment on this part for now along with lines 157 and 158 in "main". You do not need to be thinking about this part of the program right now. This will leave you with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <fstream>
//#include <bits/stdc++.h>

using namespace std;

#define N 4

int main()
{
    ifstream myfile;
    string file;
    int costMatrix[N][N];
    int i, j, row, col;

    cout << "Please enter a file name(data.txt): ";
    cin >> file;

    myfile.open(file.c_str());
    if (!myfile)
    {
        cout << "File does not exist." << endl;
    }

    myfile >> row >> col;

    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
            myfile >> costMatrix[i][j];
            cout << costMatrix[i][j] << ' ' << endl;
        }
        cout << '\n'; // newline
    }


    myfile.close();

    //cout << "\nOptimal Cost is "
    //    << findMinCost(costMatrix);

    return 0;
}

"<bits/stdc++.h>" is not a standard C++ header file and not everyone has it. I am also thinking this will include more header files than you actually need. 1 header file that you do need is "<string>".

Instead of the "#define" on line 7 consider:
 
constexpr MAXROWS{ 4 }, MAXCOLS{ 4 };

If you have a problem with "constexpr" just use "const". You will see the point shortly.

Line 13 would become: int costMatrix[MAXROWS][MAXCOLS]{};. This will also initialize the array to all zeros. Always a good idea to initialize your variables.

Line 14. Unless you have a use for "i" and "j" outside the for loops, and you do not, it is better to define these variables in the for loops.

On line 17 you open a file. From C++11 on you can use a "std::string for this. Converting it to a C string is not necessary.

Lines 20 - 23 a good start but a bad finish. Let's say the you enter the if statement and print you error message. The program will continue with line 25 , but you can not read a file that is not open, so you have no real idea what your variables will contain. What would work better is:
1
2
3
4
5
6
if (!myfile)
{
    cout << "File does not exist." << endl;

    return 1;  // <--- Leaves the program so you can fix the problem.
}


Line 25 reads the first 2 numbers in the input file. That being (82) and (83). This creates a problem with your for loops.

The following for loops would look like:
1
2
3
for (i = 0; i < 82; i++)
{
    for (j = 0; j < 83; j++)

Since your array is only 4 x 4 this would put well past the boundaries of the array. Not what you want.

What you should be using is:
1
2
3
for (i = 0; i < MAXROWS; i++)
{
    for (j = 0; j < MAXCOLS; j++)

That is just for a start.

The real part to concentrate on is reading the file and filling the array first.

After that part works you can uncomment the rest of the code and have something to work with.

Andy
@lychee

againtry provided the code to read the file in a post above. Didn't you see it??
@seeplus

Yes I did see it the code is for reading file and it works already.Then I want to ask how to find upper bound.Maybe I should ask in another forum.So sorry
Topic archived. No new replies allowed.