Link to home
Start Free TrialLog in
Avatar of polkadot
polkadot

asked on

need help - access violation - fstream

Im not sure what I'm doing wrong with this bit of code, just reading from one file, writing to another

Debuggin in VC 6.0 get these errors during run time:

First-chance exception in FunctionCalls.exe: 0xC0000005: Access Violation.
The thread 0x884 has exited with code -1073741819 (0xC0000005).
The program 'C:\Documents and Settings\Shana\Desktop\FunctionCalls\Debug\FunctionCalls.exe' has exited with code -1073741819 (0xC0000005).


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void txtStats(ifstream & in, ofstream & out);
void initalizeArray(int a[], int n);



int main()
{
      ifstream myFile ("example.txt");
      ofstream myData ("data.txt");


      if (myFile.is_open() && myData.is_open())
      {
            txtStats(myFile, myData);

            myFile.close();
            myData.close();
      }


      return 0;
}


void txtStats(ifstream & in, ofstream & out)
{
      int characterFequency[26];
      initalizeArray(characterFequency, 26);

      string word=""; //will hold one line of the file at a time
      int index=0; //will represent the index of the character in the array


      //scan the file word by word and count the number of accourances in the array

      while (! in.eof() )
    {

        in >> word;
        //check each character in the word
        for(int i=0; i< word.length() ; i++)
        {
            if(word[i] >='A' || word[i] <='Z')
                  index = word[i] - 'A';
            else
                  index = word[i] - 'a';

            characterFequency[index]++; //add one to the frequency of this character

        }

      }
        
      //output the results which are contained in the array to the output file called out

      for(int j=0; j< 26; j++)
      {
            char c = j+'a';
            out << c << "\t"<< characterFequency[j] <<"\n";
      }
}

void initalizeArray(int a[], int n)
{
      for(int i=0; i<n; i++)
            a[i]=0;
}
ASKER CERTIFIED SOLUTION
Avatar of amit_g
amit_g
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of polkadot
polkadot

ASKER

Ok, but why would there be memory overwrites if (word[i] >='A' || word[i] <='Z') is just always true?
Lets say you got 'a' in the input. So word[i] - 'A' would be 97 - 65 = 32 and so index is 32. You have only 0-26 as valid indexes in your array. Similarly for other chars it would be wrong index.
>>You have only 0-26 as valid indexes in your array

should rather be

You have only 0-25 as valid indexes in your array