-3


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
mar97
  • 21
  • 1
  • 4
  • 1
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Mar 13 '17 at 21:31
  • `word_out[j]` -- Where is `word_out` sized beforehand? Change that line to `word_out.at(j)`, and that should give you a clue as to what is happening. – PaulMcKenzie Mar 13 '17 at 21:48

1 Answers1

1

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());
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45