-2

I can't find a problem with my code. It's loading in DEV C++ but after that the window with "Program has stopped working" pop up.

fstream file;
file.open("dane1.txt");
string linia;
string tab[5];
int i = 0;

do
{   
    getline(file,linia);
    cout<<linia<<endl;
    tab[i]=linia;
    i++;
}
while(!file.eof());

file.close();

ofstream file2("wynik.txt");
if (file2)
{   

    for(int i=5;i>0;i--)
    {   
        file2<< tab[i];
        file2<< endl;

    }
}
else
{   
    cout<<"You have problem with file!"<<endl;
}

pliki.close();

I want to get lines from 1st file (dane1.txt) and then put it in diffrent order in fail "wyniki.txt"

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • Unrelated (maybe. could be overrunning the array) `while(!file.eof());` is often a not immediately fatal bug. See [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Jan 21 '19 at 20:06
  • Please provide a [mcve]. This is clearly not the code you are running. Seems like you changed the name of `file2` but missed `pliki.close()`. Anyhow, to make this compile we would need to add things that may change the behaviour of the program. – 463035818_is_not_an_ai Jan 21 '19 at 20:08
  • offtopic: you dont need to close the files, their destructor already does that for you – 463035818_is_not_an_ai Jan 21 '19 at 20:14

1 Answers1

3
string tab[5];

// ...

for(int i=5;i>0;i--)
{   
    file2<< tab[i];
    file2<< endl;

}

The first iteration of this for loop attempts to access tab[5] which, of course, doesn't exist since the five-element tab array contains only tab[0] through tab[4]. Undefined behavior, and the near-certain reason for your program crashing.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148