What I would like to do:
- Read data from text file
- Display data from text file
- Add new data to text file
- Save new data to text file
The file format used is as follows:
Number of items in text file (3)
Name 1
Number 1
Date 1
Name 2
Number 2
Date 2
Name 3
Number 3
Date 3
etc.....
The code I have:
struct Shoes {
char Name[20];
unsigned int Number;
double Size;
};
int Main()
{
//Load file into struct////////////////////////////
fstream input_file;
// open the file
input_file.open(FILENAME);
Shoes Shoe[MAX];
int i = 0; //counter
int num; //number of components in file
input_file >> num;
for(int i=0; i<num; i++)
{
input_file >> Shoe[i].Name >> Shoe[i].Number >> Shoe[i].Size;
}
/////////////////////////////////////////////////////
//Add new element/////////////////////////////
cout << "Enter Name, Number and Date: ";
cin >> Shoe[i].Name >> Shoe[i].Number >> Shoe[i].Size;
//////////////////////////////////////////////
//Diaplay all + new element//
for(int i=0; i<num; i++)
{
cout << "\n" << Shoe[i].Name << "\n" << Shoe[i].Number << "\n" << Shoe[i].Size << "\n\n";
}
///////////////////////////
//Write/save all to file//
for(int i=0; i<num+1; i++)
{
input_file << Shoe[i].Name << "\n" << Shoe[i].Number << "\n" << Shoe[i].Size << "\n\n";
}
///////////////////////////
input_file.close();
}
The problem:
I can read the data from the text file into a struct array and add a new element to the array. But the code I have used does not work to write/save the data to the array. Could anyone help me or suggest a better way to do this. Ideally seperate functions to load, add a new element, display and save to a .txt file are needed.