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