0

I'm trying to write a program for a Caesar Cipher, and right now I'm working on the function to find the key to shift the cipher.

Now the problem arises that while it reads the file, the program breaks and I get the error:

"Exception thrown at 0x89012914 in ConsoleApplication11.exe: 0xC0000005: Access violation executing location 0x89012914. If there is a handler for this exception, the program may be safely continued."

Here's the code I have so far, is there anything obvious that I'm overlooking?

int findKey(string& file);

int main()
{

    string inputFileName;


    cout << "Input file name: ";
    getline(cin, inputFileName);

    findKey(inputFileName);




}

int findKey(string& file)
{
    string reply;
    ifstream inFile;
    char character;
    int count[26] = { 0 };
    int nGreatest = 0;

    inFile.open(file.c_str());

    if (!inFile.is_open())
    {
        cout << "Unable to open input file." << endl;
        cout << "Press enter to continue...";
        getline(cin, reply);
        exit(1);

    }

    while (inFile.peek() != EOF)
    {
        inFile.get(character);
        cout << character;

        if (int(character) >= 65 || int(character) <= 90)
        {
            count[(int(character)) - 65]++;
        }
        else if (int(character) >= 97 || int(character) <= 122)
        {
            count[(int(character)) - 97]++;
        }
    }

    for (int i = 0; i < 26; i++)
    {
        if (count[i] > nGreatest)
            nGreatest = count[i];

    }

    cout << char(nGreatest) << endl;

    return 0;
}
  • [Have a look a this](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Rakete1111 Aug 02 '16 at 02:30

1 Answers1

1
if (int(character) >= 65 || int(character) <= 90)

Since a newline character, '\n' is ASCII 10, which is less than or equal to 90, this if statement will evaluate to true, and ...

count[(int(character)) - 65]++;

... attempt to increment count[10-65], or count[-55]. Things pretty much go off the rails, from this point (since every character, is either at least 65, or less than or equal to 90, this will always evaluate to true).

P.S. It took me just a few minutes to locate this bug, using a debugger, by stepping through the code, one line at a time (I couldn't immediately see it myself) and examining all variables. You should invest some time learning how to work with your debugger. Makes it easier to find one's own bugs, without having to ask strangers on the intertubes, for help.

Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106