Saving an array to text file! HELP!

Had another quick question... I want to serialize my array down and up. But right now I'm having trouble saving my array into 'data.txt' because it only saves one cycle of the loop and not every input i put.

Once that is fixed I wanted to serialize up or get inputs from the already saved 'data.txt' so that my program 'remembers' where it left off.

Thanks! So far i got.. !


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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ios;

#include <string>
using std::string;

#include <cstdlib>

#include <fstream>
using std::ofstream;
using std::ifstream;

struct course
{
 string title;
 int yearTaken;
 double units;
 char grade;
};

int main()
{
 course a[100];
 int size = 0;

//serialize up  - want to be able to read inputs into the array from data.txt
ifstream fin;
fin.open("data.txt");
if (fin.good())
{
 string buf;
 for (int i = 0; i < size; i++)
 {
  getline (fin, buf);
  if (buf == "EOF") break; //eof=end of file
  buf = a[size].title;
  size++;
 }
 fin.close();
}

for (int i = 0; i < 100; i++) // main loop
  {
  cout << " Course      Year  Units   Grade\n";
  cout << "---------    ---  -------  ------\n";

  for (int j = 0; j < size; j++)

  cout << a[j].title << "   " << a[j].yearTaken << "   "  << a[j].units  << "      " << a[j].grade << endl;
  cout << endl;

  cout << "Enter course #" << size+1 <<" [Q to exit]: ";
  getline(cin, a[size].title);

  if (a[size].title == "q")break;
  if (a[size].title=="Q") break;

  string buf;
  cout << "What year was " << a[size].title << " taken? [e.g, 2016]: " ;
  cin >> buf; a[size].yearTaken = atoi(buf.c_str());
  cin.ignore(1000, 10);

  cout << "How many units was " << a[size].title << "?: " ;
  cin >> buf; a[size].units = atoi(buf.c_str());
  cin.ignore(1000, 10);

  cout << "What was your grade?[? for in-progress or planned]: ";
  cin >> a[size].grade;
  cin.ignore(1000, 10);
  cout << endl;

  size++;
  }

  //serialize down - partially working, need to save more than 1 loop
  ofstream fout;
  fout.open("data.txt");
  for (int j = 0; j < size; j++)
  {
   fout << a[j].title << endl;
   fout << a[j].yearTaken << endl;
   fout << a[j].units << endl;
   fout << a[j].grade << endl;
   fout << "EOF\n";
   fout.close();
  }

}
Last edited on
Note: Serialize down refers to saving it and serialize up to taking the info from the data.txt
I think you need to check your data.txt first.
I believe all the data are written, and you read only one record (one line)
Oh? Is there a way to save more than just one line? Not sure if the way i did it is correct
Topic archived. No new replies allowed.