Read/Write to file

My program works until I read a file and then if I do anything it makes a message pop up that says "Unhandled exception at 0x009622cf in Read_Write.exe: 0xC0000005: Access violation reading location 0x6c654839."
I can't find what the problem is. My teacher gave me most of the program I just put the reading part and the writing part together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 #include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
double write();
double read();
int a;	char replace[10];
	char alpha[10];
ofstream myfile;
void main () {
	do{cin>>a;switch (a){
	case 1: write(); break;
	case 2: read(); break;

	}
	}while(a!=0);

}

double write()
{
  cout<<"not here";
  getchar();

  myfile.open ("data.txt");
  for (int i=1; i<=50; i++)
  {
myfile << 5*i <<"Hello"<< "\t";
if (2*i%10==0)
  myfile << "\n"; 
  }
  myfile.close();
  return 0;
}

double read()
{

 int i;

ifstream indata; // indata is like cin
  indata.open("data.txt"); // opens the file
    if(!myfile) { // file couldn't be opened
      cerr << "Error: file could not be opened" << endl;
      exit(1);
}
i=0;
indata >> alpha[i];
  while ( !indata.eof() ) 
  { // keep reading until end-of-file
cout << "The next letter is " << alpha[i] << endl;
i++;
//
indata >> alpha[i]; // sets EOF flag if no value found
  }

  for(int j=0;j<=i;j++){
	  replace[j]=alpha[j];
	  alpha[j]=0;
  }
  alpha[i]=0;
  indata.close();
  cout << "End-of-file reached.." << endl;
  for(int j=0;j<=i;j++)cout<<alpha[j];
getchar();
	return 0;
}


instead of !indata.eof() try indata.good(). My guess is that you are reading beyond the end of the file.
The output file contains 450 characters. The program attempts to read this into an array of 10 characters. Something has to give. In this case, modifying memory areas outside the array boundaries results in corruption of data with unpredictable (but very bad) results.
Last edited on
closed account (Dy7SLyTq)
you could use a string instead of an array
Thank you for the help. I did what you told me Chervil and it works now. Thanks. This had caused me quite a bit of frustration.
Topic archived. No new replies allowed.