I have problem with my code.
When I run this code, the correct answer appears. After a while i see an error showing that "program has stopped working" (0xC0000005). Have you got any idea why does the program not work properly? Everything seems to be ok.
#include <iostream>
#include <fstream>
using namespace std;
int k = 107;
string word;
string word_out;
fstream plik;
fstream plik_out;
int main() {
plik.open("Dane_PR2/dane_6_1.txt", ios::in);
plik_out.open("Dane_PR2/wynik_6_1.txt", ios::out);
for (int i = 0; i < 100; i++)
{
plik >> word;
for (int j = 0; j < word.length(); j++)
{
while (k>26)
{
k=k-26;
}
word_out[j] = word[j] + k;
if (word_out[j] > 90) word_out[j] = word_out[j] - 26;
cout << word_out[j];
plik_out << word_out[j];
}
cout << endl;
plik_out << endl;
}
plik.close();
plik_out.close();
return 0;
}
here you have input data - txt file which my program reads:
http://www74.zippyshare.com/v/4i6fg2NB/file.html
One major issue is that you are accessing the word_out
string out-of-bounds:
word_out[j] = word[j] + k;
word_out
at the time that this line is executed is empty, thus there is no index j
within the string.
Change that line to:
word_out.at(j) = word[j] + k;
and you should now get an std::out_of_range
exception thrown instead of a cryptic access violation error.
So you need to fix your program so that you're not going out of bounds. One possible way is to size the word_out
string before you use it.
plik >> word;
word_out.resize(plik.size());