.exe stoped working

help me to fix

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
int i, plotas, a, p, k, x1[i], x2[i], y1[i], y2[i];
int plotas1 = 0;
ifstream fd("Duomenys.txt");
ofstream fr("Rezultatai.txt");
fd >> a >> p;
fd >> k ;
for (int i = 0; i < k; i++) {
fd >> x1[i] >> y1[i] >> x2[i] >> y2[i];
plotas += (x2[i] - x1[i]) * (y2[i] - y1[i]);
}
fr << plotas << endl;
fd.close();
fr.close();
return 0;
}

Think, what is the size of those arrays?
There are many places where this program could go wrong, but the first thing wrong is that you are trying to make 4x arrays with the size being an uninitialized variable, i.

On line 8, you declare an int i, but then also x1[i], x2[i], y1[i], y2[i].

An array needs to have a compile-time constant as its size!

It looks like you want to have the arrays be of size k, but you don't initialize your k variable either. Your fd file stream eventually puts a value into k, but the main problem is still that your x1, x2, y1, and y2 arrays don't have a legal size.

When you declare your for loop, your new i variable also shadows the originally-declared i variable.

I would suggest something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
    const int Max_Size = 100; // Or whatever you deem appropriate
    int x1[Max_Size];
    int y1[Max_Size];
    int x2[Max_Size];
    int y2[Max_Size];

    int plotas = 0;
    int a, p, k;

    // ...

    fd >> a >> p;
    fd >> k;

    for (int i = 0; i < k; i++) {
        fd >> x1[i] >> y1[i] >> x2[i] >> y2[i];
        plotas += (x2[i] - x1[i]) * (y2[i] - y1[i]);
    }
   // ...
}


Of course, your file also needs to be formatted correctly, should be in the form (replacing the letters with actual numbers)

a p
k

x1 y1 x2 y2
x1 y1 x2 y2
x1 y1 x2 y2
...


You also never use your a or p variables. If you don't want to deal with silly, error-prone constructs such as "Max_Size", I would suggest using std::vectors -- http://www.cplusplus.com/reference/vector/vector/
Last edited on
Topic archived. No new replies allowed.