Strange integer reading from file C++
Really tried to look around, used search. Used Google, tried many ways, but I can't figure this out. (And I guess it's really easy for anyone who 'speaks fluent C++'.)
It's a really easy homework, but I have no idea why does it work this way.
Here is the code:int temp;
string fname;
cout << "Kerem a fajlnevet: ";
cin >> fname;`
ifstream f;
f.open(fname.c_str());
int szam_madar, szam_helyseg;
f >> szam_madar;
f >> szam_helyseg;
int matrix[szam_helyseg * szam_madar];
for (int i = 1; i <= szam_helyseg; i++)
{
for(int j=1; j <= szam_madar; j++)
{
f >> matrix[i*szam_madar + j];
}
}
maximalisHelyseg(matrix,szam_helyseg,szam_ma开发者_运维问答dar);`
And the text I'm using at the read:
5 5 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1It should create a 5x5 array, then fill it up in order.
Now... the result is quite different. For the first few array member it gives something like 2686048, 4686232 and so on.you have stuff like:
for (int i=1; i <= szam_helyseg; i++)
{
for(int j=1; j <= szam_madar; j++)
{
f >> matrix[i*szam_madar + j];
}
}
But array indices count from 0, so the easiest way to do stuff is
for (int i=0; i < szam_helyseg; i++)
{
for(int j=0; j < szam_madar; j++)
{
f >> matrix[i*szam_madar + j];
}
}
etc. You can see that in the initial iteration, the index computed is 0, whereas in the original, it starts at szam_madar + 1
(which is a sign that something is wrong).
Also, variable length arrays are not standard C++ (referring to the line int matrix[szam_helyseg * szam_madar];
). Use the array new
operator, or (better), a vector<int>
.
C/C++ arrays as 0 based. Their indices start from 0 and go to length-1. The first bug in your program is the indices of this loop. You should start from [0, szam_helyseg-1] and [0, szam_madar-1]
for (int i=1; i <= szam_helyseg; i++)
{
for(int j=1; j <= szam_madar; j++)
{
f >> matrix[i*szam_madar + j];
}
}
Also, since you are trying to represent a Matrix, it would beneficial to the clarity of the code if you use a 2D array. That will get rid of the index arithmetic (like i*szam_madar + j) which could also be a source of hard to find bugs.
精彩评论